我想檢查如何等待/通知在java中工作。等待()/通知()同步
代碼:
public class Tester {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
synchronized (t) {
try {
System.out.println("wating for t to complete");
t.wait();
System.out.println("wait over");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyRunnable implements Runnable {
public void run() {
System.out.println("entering run method");
synchronized (this) {
System.out.println("entering syncronised block");
notify();
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("leaving syncronized block");
}
System.out.println("leaving run method");
}
}
輸出返回
wating for t to complete
entering run method
entering syncronised block
//sleep called
leaving syncronized block
leaving run method
wait over
我所期待的通知()時執行的等待將超過& System.out.println("wait over");
將得到打印。但它似乎只在t
完成其run()
時才被打印出來。
你沒有在同一個對象上同步 – MadProgrammer
MyRunnable.this == r!= t –
@ raul8編輯問題並粘貼到答案中使正確答案無效。最好再增加一個問題。 –