package a0002;
public class SimpleWN {
final static Object object = new Object();
public static class T1 extends Thread{
@Override
public void run() {
synchronized (object) {
System.out.println(System.currentTimeMillis()+":T1 start!");
System.out.println(System.currentTimeMillis()+":T1 wait for object");
try {
object.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(System.currentTimeMillis()+":T1 end!");
}
}
}
public static class T2 extends Thread{
@Override
public void run() {
synchronized (object) {
System.out.println(System.currentTimeMillis()+":T2 start! notify one thread");
object.notify();
System.out.println(System.currentTimeMillis()+":T2 end!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Thread t1 = new T1();
Thread t2 = new T2();
t1.start();
t2.start();
}
}
在上述代码中,开启了两个线程T1和T2。T1执行了object.wait()方法。执行wait()方法前,T1先申请object的对象锁。因此,在执行object.wait()时,它是持有object锁的。wait()方法执行后,T1会进行等待,并释放object锁。T2在执行notify()之前也会先获得object对象锁。这里为了让实验效果更明显,特意安排在notify()执行之后,让T2休眠2秒钟,这样做可以更明显的说明,T1在得到notify()通知后,还是会先尝试重新获得object的对象锁。