我想弄清楚如何使用等待&通知,所以我寫了這個小例子,有幾架飛機在起飛前等待跑道清除,我遇到的問題是,當一架飛機起飛,並調用notifyAll(),只有一個線程似乎被喚醒,即我希望所有的線程報告他們已被通知,但仍在等待。實際發生的情況是,只有一個線程被喚醒,其餘的什麼都不會執行。爲什麼只有一個線程被喚醒,我該如何解決?爲什麼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();
}
}
感謝您抽出寶貴時間來幫助我:)
實際上,OP的代碼寫入方式,其他線程沒有等待,所以他們從來沒有看到通知。看到我的答案進行詳細分析(和修復)。 –