Java等待通知机制
1.等待通知机制,是指一个线程A调用了对象O的wait()方法进入等待状态,而另一个线程B调用了对象O的notify()或者notifyall()方法,线程A收到通知后从对象O的wait()线程返回,进而执行后续操作。
package Package_1120;
/**
* @Discription 等待通知机制
* @Author HY
* @Version V1.0
* @Data 2020年11月20日 上午9:14:42
*/
public class WaitTest {
public static void main(String args[]) {
try {
Thread thread1 = new T1();
Thread thread2 = new T2();
thread1.start();//开启线程T1
thread2.start();//开启线程T2
} catch (Exception e) {
e.printStackTrace();
}
}
final static Object person = new Object();
public static class T1 extends Thread {
public void run() {
synchronized (person) {
System.out.println(System.currentTimeMillis() + " T1 come");
try {
System.out.println(System.currentTimeMillis() + " T1 wait");
person.wait();
} catch (InterruptedException r) {
r.getStackTrace();
}
System.out.println(System.currentTimeMillis() + " T1 over");
}
}
}
public static class T2 extends Thread {
public void run() {
synchronized (person) {
System.out.println(System.currentTimeMillis() + " T2 come");
person.notify();
System.out.println(System.currentTimeMillis() + " T2 over");
try {
Thread.sleep(5000);
} catch (InterruptedException r) {
r.getStackTrace();
}
}
}
}
}
上述代码简单流程图如下:
2.注意事项
(1)使用wait()、notify()和notifyall()方法时需要先对调用对象加锁,即上述的person 对象,wait()方法只能写在同步代码块和同步方法中。
(2)调用wait()方法后,线程T1由RUNNING状态变为WAITING,将其放置到对象的等待队列,同时线程T1释放对象锁。
(3)notify()方法调用后,等待线程T1不会从wait()返回,需要等到T2的线程释放锁之后,即在synchronized同步代码块执行完毕后才会返回。
(4)注意T1线程重wait()方法返回的前提是获得了调用对象的锁。
(5)notify()方法将等待队列中的一个线程移动到同步队列即锁池中。