//notify 通知,通告
//lock 锁;水闸,船闸;(机器部件等的)锁定;
/*
wait() 与 notify()
wait():令当前线程挂起并放弃CPU,使别的线程可访问并修改共享资源,而当前线程排队等候再次对资源的访问
notify():唤醒正在排队等待同步资源的线程结束等待
Java.lang.Object提供的这两个方法只有在synchronized方法或synchronized代码块中才能使用,
否则会报java.lang.IllegalMonitorStateException异常
*/
public class TestWaitNotify {
static Object lock = new Object();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock){
System.out.println("start execute thread A");
try {
Thread.sleep(1000);
System.out.println("A execute the things one second");
System.out.println("A will release lock,into wait");
lock.wait();
System.out.println("A want to keep doing something ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock){
try {
System.out.println("start execute Thread B,B need 3 seconds to do something");
Thread.sleep(3000);
System.out.println("B do thing in three seconds, then awaken (唤醒)A");
lock.notify();
System.out.println("B feels uncomfortable and has to do something for two seconds");
Thread.sleep(2000);
System.out.println("B is about to quit(退出)");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}