? asked in 電腦與網際網路程式設計 · 1 decade ago

Java的Thread內的wait及notify

class ThreadB extends Thread{

int total;

public void run(){

synchronized(this){

for (int i = 0 ; i< 100 ;i++)

total += i;

}

notify();

}

}

public class ThreadA {

public static void main(String[] args) {

ThreadB b = new ThreadB();

b.start();

synchronized(b){

System.out.println("waiting for b to complete...");

try {

b.wait();

} catch (InterruptedException e) {

System.out.println("total is : " + b.total);

}

}

}

}

以上程式,我期望main thread會先搶到b的鎖,然後wait,

但事實上好像沒辦法,實際執行後,大多是ThreadB 先搶到執行,所以就會產生

waiting for b to complete...

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException

at java.lang.Object.notify(Native Method)

at ThreadB.run(ThreadA.java:15)

的執行結果,請問一下,要怎麼確保

main thread會先搶到b的鎖?

2 Answers

Rating
  • 七喜
    Lv 5
    1 decade ago
    Favorite Answer

    java.lang.IllegalMonitorStateException

    違法的監控狀態異常。當某個線程試圖等待一個自己並不擁有的對象

    所以只要把notify();搬進synchronized(this){這裡面}就可以Compile過關了

    class ThreadB extends Thread{

    int total;

    public void run(){

    synchronized(this){

    for (int i = 0 ; i< 100 ;i++)

    total += i;

    this.notify();

    }

    }

    }

    public class ThreadA {

    public static void main(String[] args) {

    ThreadB b = new ThreadB();

    b.start();

    synchronized(b){

    System.out.println("waiting for b to complete...");

    try {

    b.wait();

    } catch (InterruptedException e) {

    System.out.println("total is : " + b.total);

    }

    }

    }

    }

    Source(s): wei
  • 1 decade ago

    「期望main thread會先搶到b的鎖」

    這並不是什麼好的 idea,建議您還是換個設計方式。

Still have questions? Get your answers by asking now.