1 つのスレッドが「Hello」を出力し、別のスレッドが「World」を出力するとします。次のように、一度は成功しました。
public class InterThread {
public static void main(String[] args) {
MyThread mt=new MyThread();
mt.start();
synchronized(mt){
System.out.println("Hello");
try {
mt.wait();
i++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyThread extends Thread{
public void run(){
synchronized(this){
System.out.println("World!");
notify();
}
}
}
複数回の印刷、たとえば 5 回の印刷を行うにはどうすればよいですか。同期ブロックの周りに for ループを入れてみましたが、役に立ちませんでした。