【发布时间】:2016-04-03 01:14:54
【问题描述】:
我试图弄清楚如何使用等待和通知,所以我写了这个小例子,其中有几架飞机在起飞前等待跑道清理干净,我遇到的问题是,当飞机起飞并调用 notifyAll(),似乎只有一个线程被唤醒,即我希望所有线程都报告它们已收到通知,但仍在等待。实际发生的是只有一个线程被唤醒,其余的什么也不做。为什么显示只有一个线程被唤醒,我该如何解决?
class Plane extends Thread
{
Runway runway;
Plane(int id, Runway runway)
{
super(id + "");
this.runway = runway;
}
public void run()
{
runway.taxi();
runway.takeoff();
}
}
class Runway
{
boolean isFull;
Runway()
{
isFull = false;;
}
public synchronized void taxi()
{
System.out.println(Thread.currentThread().getName() + " started to taxi");
while(isFull)
{
System.out.println(Thread.currentThread().getName() + " is queued");
try
{
wait();
}
catch(InterruptedException e){}
}
isFull = true;
System.out.println(Thread.currentThread().getName() + " entering runway");
}
public synchronized void takeoff()
{
try
{
Thread.currentThread().sleep(1000);
}
catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName() + " took off");
isFull = false;
notifyAll();
}
public static void main(String[] args)
{
Runway runway = new Runway();
new Plane(1, runway).start();
new Plane(2, runway).start();
new Plane(3, runway).start();
new Plane(4, runway).start();
}
}
感谢您花时间帮助我:)
【问题讨论】:
标签: java multithreading wait notify