ThreadAのコメント行に示されているように、ブロックのtimlesProc(100);
内側または外側に配置する違いはありますか?synchronized
私の理解によると、両方のスレッドが実行モードにあり、両方を同時に実行できるため、違いはありません。しかし、実験によると、timlesProc(100);
が内部にある場合synchronized
、常に最初に実行され、次にb.sync.wait();
「永遠に待機」する問題はありません。timlesProc(100);
外にいるとき、synchronized
私はいつも「ずっと待っている」と感じます。それはなぜですか、それとも私の理解は正しくありませんか?
class ThreadA {
public static void timlesProc(int count)
{
for(int i=0;i<count;i++)
{
System.out.println(Thread.currentThread().getName()+" "+ Integer.toString(i));
}
}
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
//timlesProc(100);
synchronized(b.sync)
{
timlesProc(100);
try
{
System.out.println("Waiting for b to complete...");
b.sync.wait();
System.out.println("waiting done");
} catch (InterruptedException e) {}
}
}
}
class ThreadB extends Thread {
Integer sync = new Integer(1);
public void run() {
synchronized(sync)
{
sync.notify();
System.out.println("notify done");
}
}
}