-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である)、それの状態から抜け出します自動的に。
'notify'の後に来る' wait'sは影響を受けません。ここで何をしようとしているのかははっきりしない。あなたのプログラムはシングルスレッドです。 –
スレッドインスタンスではwait()とnotify()を使用していません。スレッドでやり直してからwait()が自動的に待ち状態になります。 –
マルチスレッドプログラムを使用でき、 'wait'と' notify'を対応する 'Thread'オブジェクトです。 –