IT十八掌作业_java基础第八天_多线程

/**

*1. 5辆汽车过山洞,依次经过山洞。每辆车通过山洞花费10秒,使用多线程实现。

*/


//山洞

class Cave

{

}


//汽车

class Car extends Thread

{

private String name;

private Cave cave;

public Car()

{}


public Car(Cave cave ,String name)

{

this.cave = cave;

this.name = name;

}


public void run()

{

synchronized(cave)

{

System.out.println(name + ",进洞了!");

try

{

Thread.sleep(1000);

System.out.println(name + "出洞了");

}

catch (Exception e)

{

System.out.println("错了!");

}

}

}

}


class ThreadDemo3

{

public static void main(String[] args)

{

Cave cave = new Cave();

Car c1 = new Car(cave,"C1");

Car c2 = new Car(cave,"C2");

Car c3 = new Car(cave,"C3");

Car c4 = new Car(cave,"C4");

Car c5 = new Car(cave,"C5");


c1.start();

c2.start();

c3.start();

c4.start();

c5.start();



}

}


/**

*2. 用多线程模拟蜜蜂和熊的关系。

   蜜蜂是生产者,熊是消费者。蜜蜂生产蜂蜜是累加的过程,熊吃蜂蜜是批量(满100吃掉)的过程。

   生产者和消费者之间使用通知方式告知对方。注意不能出现死锁的现象。

*/


class SmallBee extends Thread

{

private java.util.List<Integer> list ;

final static int MAX = 100;

private String name;


public SmallBee(String name,java.util.List<Integer> list)

{

this.name = name;

this.list = list;

}


public void run()

{

while (true)

{

synchronized(list)

{

//添加蜂蜜

if (list.size() < MAX)

{

list.add(new Integer(list.size()));

try

{

Thread.sleep(100);

}

catch (Exception e)

{

}

System.out.println(name + ":" + list.size());

//通知 线程 == 熊 

list.notify();

}

//蜂蜜满了--- 等待 

if (list.size() == MAX)

{

System.out.println("蜂蜜满了,快来吃。。。");

try

{

list.wait();

}

catch (Exception e)

{

}

}

}

}

}


}


class Bear extends Thread

{

private java.util.List<Integer> list ;


private String name;


public Bear(String name , java.util.List<Integer> list)

{

this.name = name;

this.list = list;

}


public void run()

{

while (true)

{

synchronized (list){

//查看蜂蜜是否满了

if (list.size() >= 100)

{

System.out.println("开始吃蜂蜜了,蜂蜜数量:"+list.size());

//remove 前100个元素

for (int j = list.size()-1;j >= 0  ;j-- )

{

Integer tmp = list.remove(j);

System.out.println(name + "吃了"+tmp);

}


System.out.println("已经吃完了,蜂蜜还剩余:"+list.size());


list.notify();


}else

{

try

{

System.out.println("等蜂蜜吃");

list.wait();

}

catch (Exception e)

{

}

}

}

yield();

}

}

}


class ThreadDemo4

{

public static void main(String[] args)

{

java.util.List<Integer> list = new java.util.ArrayList<Integer>();


SmallBee sb1 = new SmallBee("S1",list);

SmallBee sb2 = new SmallBee("S2",list);

SmallBee sb3 = new SmallBee("S3",list);


Bear b1 = new Bear("熊大",list);

Bear b2 = new Bear("熊二",list);


sb1.start();

sb2.start();

sb3.start();

b1.start();

b2.start();


}

}


你可能感兴趣的:(java,基础,第八天)