public class Thread04 {
final Object object = new Object();
Runnable rb4 = new Runnable() {
public void run(){
synchronized (object){
System.out.println("T1 start!");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
object.notify();
System.out.println("T1 end!");
}
}
};
Runnable rb5 = new Runnable() {
public void run(){
synchronized (object){
System.out.println("T2 start!");
object.notify();
System.out.println("T2 end!");
}
}
};
public static void main(String[] args) {
Thread04 th = new Thread04();
new Thread(th.rb4).start();
new Thread(th.rb5).start();
}
}
PHP中文网2017-04-18 10:55:24
rb5's object.notify(); is called when rb4 has not entered the wait state because it is still waiting for the lock. Thread start does not mean that it will run() by itself immediately, which means that the run() of the thread that starts() after it is likely to be executed first.
迷茫2017-04-18 10:55:24
rb4
在运行获得object
的对象锁,输出T1 start!
,然后调用wait()
,该方法会让rb4
挂起,同时释放锁,阻塞。 这时候rb5
获得锁,输出T2 start!
。然后调用object.notify();
,虽然这里打算让rb4
运行,但是rb5
的锁并没有释放,所以rb4
还是处于阻塞。 rb5
还是继续运行,输出T2 end!
。 rb5
运行结束,释放锁, rb4
运行输出T1 end!
。