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();
}
}
rb5 的 object.notify(); 调用时 rb4 还没有进入 wait 状态,因为还在等待锁。线程 start 并不代表马上会自行 run(),也就是说后 start() 的线程的 run() 很有可能先执行。