-4
在下面的代碼中爲什麼wait()之後的部分不會執行。 即使在主線程擁有鎖的對象中存在notify()也是如此。爲什麼MainClass不會從等待狀態中出來
public class MainClass {
public static void main(String[] args) {
Demo dm = new Demo();
dm.add();
synchronized (dm) {
try {
System.out.println("going to wait");
dm.wait();
System.out.println("after wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(dm.result);
}
}
}
class Demo {
int result;
public void add(){
System.out.println("in demo");
synchronized (this) {
System.out.println("in demo syn block");
for(int i=0;i<=10;i++) {
result=i+result;
}
System.out.println("IN demo:"+result);
notify();
}
}
}
}
我需要知道的是,爲什麼等待後的代碼()不執行即使通知()是there.If我嘗試解決這個使用線程然後等待(),把它弄出來的狀態自動。
任何'wait'後面的'notify'都不受影響。目前尚不清楚你想在這裏做什麼。你的程序是單線程的。 –
wait()和notify()不會與線程實例一起使用..如果我嘗試使用線程,那麼wait()會自動出現等待狀態 –
您可以擁有多線程程序並且不使用wait和notify他們相應的'Thread'對象。 –