//測驗wait被喚醒后執行緒從哪里開始執行
/*t1啟動 列印t1begin ,然后wait,釋放鎖Num n 。
t2啟動 , 列印t2begin ,然后notifyAll ,應當列印t2over,結束run后,
t1可重新拿到鎖,應當列印t1over。
但程式卡住,未列印t2over,與t1over,說明notifyAll后,程式就卡住了,這是為何。*/
public class WaitTest {
public static void main(String[] args) {
Num n = new Num(10);
Thread t = new MyThread(n);
Thread t2 = new MyThread(n);
t.setName("t1");
t2.setName("t2");
t.start();
//確保t1在t2前運行
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}
class MyThread extends Thread{
Num n;
public MyThread(Num n) {
this.n = n;
}
@Override
public void run() {
synchronized (n){
System.out.println(currentThread().getName() + "begin");
try {
n.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(currentThread().getName() + "over");
}
}
}
class MyThread2 extends Thread{
Num n;
public MyThread2(Num n) {
this.n = n;
}
@Override
public void run() {
synchronized (n) {
System.out.println(currentThread().getName() + "begin");
n.notifyAll();
System.out.println(currentThread().getName() + "over");
}
}
}
class Num{
int num;
public Num(int num) {
this.num = num;
}
}
uj5u.com熱心網友回復:
wait操作阻塞在哪里,被喚醒時,就從哪里開始執行。uj5u.com熱心網友回復:
正好剛才回復了類似的問題,看看這里uj5u.com熱心網友回復:
以后發帖的時候盡量把代碼寫在[code=語言型別]代碼內容[/code]里面今天重新看了下你的代碼,你執行緒2還是MyThread物件,應該new 一個MyThread2物件
uj5u.com熱心網友回復:
謝謝你,其實剛發完這個貼我就看到錯誤,就立刻結貼了。 不過這種錯誤真的好難發現,你這個方法很實用!謝謝啦
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/22639.html
標籤:Java SE
上一篇:JavaScript的資料型別
