场景
- 调用wait的线程的唤醒,一般通过notify和notifyAll,但是两者之间有什么区别呢?
分析
- 线程调用synchronized方法或者synchronized代码块需要获取对象锁,如果没有获取则进入锁池
- 线程调用wait方法进入等待池,此时可以通过锁对象调用 notify,notifyAll方法(第三方线程获取锁对象的synchronized的方法中释放),释放等待池线程进入锁池。
- notify只释放一个等待池中的线程,优先级的高的机会大些。而notifyAll则释放等待池中所有的线程.
例子
public class ThreadWaitAndNotifyDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(ThreadWaitAndNotifyDemo::sayHelloWorld);
thread.setName("T1");
thread.start();
Thread thread1 = new Thread(ThreadWaitAndNotifyDemo::sayHelloWorld);
thread1.setName("T2");
thread1.start();
Object monitor = ThreadWaitAndNotifyDemo.class;
synchronized (monitor) {
monitor.notify();
}
System.out.println("Hello next ------->");
}
private static void sayHelloWorld()
{
Object monitor = ThreadWaitAndNotifyDemo.class;
synchronized (monitor) {
try {
System.out.printf("线程【%s】<--------------->进入等待状态 \n", Thread.currentThread().getName());
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("线程[%s] 恢复执行: <==============> Hello World!\n", Thread.currentThread().getName());
}
}
}
线程【T1】<--------------->进入等待状态
线程【T2】<--------------->进入等待状态
Hello next ------->
线程[T1] 恢复执行: <==============> Hello World!