5辆汽车过山洞,依次经过山洞。每辆车通过山洞花费10秒,使用多线程实现。
class Bus extends Thread
{
private String name;
private static Object obj = new Object();
public Bus(String name)
{
this.name = name;
}
public String getBusName()
{
return name;
}
public void run()
{
synchronized(obj)
{
System.out.println(Thread.currentThread().getName()+"\t"+this.getBusName()+"正在穿越山洞!!");
try{
Thread.sleep(10*1000);
}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"\t"+this.getBusName()+"已经穿过山洞了");
}
}
}
class ThreadDemo
{
public static void main(String[] args)
{
Bus t1 = new Bus("一号车");
Bus t2 = new Bus("二号车");
Bus t3 = new Bus("三号车");
Bus t4 = new Bus("四号车");
Bus t5 = new Bus("五号车");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
/*
2. 用多线程模拟蜜蜂和熊的关系。
蜜蜂是生产者,熊是消费者。蜜蜂生产蜂蜜是累加的过程,熊吃蜂蜜是批量(满100吃掉)的过程。
生产者和消费者之间使用通知方式告知对方。注意不能出现死锁的现象。
*/
//生产者
import java.util.*;
class Beans extends Thread
{
final static int MAX = 100;
List<Integer> list;
String name;
public Beans(List<Integer> list,String name)
{
this.list = list;
this.name = name;
}
public void run()
{
int i =1;
while(true)
{
synchronized(list)
{
int size = list.size();
if(size<MAX)
{
list.add(new Integer(i));
System.out.println(name+"蜜蜂生产第" + i+"份蜜!!");
i ++ ;
list.notifyAll(); //唤醒属于当前对象的等待队列中的所有线程,拿到获取锁资格。
}
else //如果蜂蜜数量大于等于100,通知熊可以吃了
{
try
{
list.wait();//使当前线程进入等待队列中,并释放锁,允许其他线程进入同步代码块,
}
catch(Exception e){}
}
}
}
}
}
//消费者
class Bear extends Thread
{
List<Integer> list;
String name;
public Bear(List<Integer> list,String name)
{
this.list = list;
this.name = name;
}
public void run()
{
while(true)
{
synchronized(list)
{
int size = list.size();
if(size>=100)
{
for(int i=0;i<size;i++)
{
list.remove(0);
}
System.out.println(name+"吃了100份蜂蜜!!-----------------");
list.notify();//唤醒属于当前对象的等待队列中的所有线程,准备获得锁。
}
else
{
try
{
list.wait();
}
catch(Exception e){}
}
}
}
}
}
class ThreadDemo2
{
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
Beans t1 = new Beans(list,"lucy");
Beans t2 = new Beans(list,"lili");
Bear t3 = new Bear(list,"熊大");
t1.start();
t2.start();
t3.start();
}
}