龙空技术网

java的notify和notifyAll有什么本质的区别

万物生的好物 105

前言:

眼前姐妹们对“javanotify”大约比较看重,小伙伴们都想要分析一些“javanotify”的相关内容。那么小编在网络上网罗了一些对于“javanotify””的相关文章,希望小伙伴们能喜欢,各位老铁们一起来了解一下吧!

notifyall,可以唤醒所有处于wait状态的线程,使其重新进入锁的争夺队列中,而notify只能唤醒一个。

这里注意,任何时候只有一个线程可以获得锁,也就是说只有一个线程可以运行同步锁synchronized 中的代码,

notifyall只是让处于wait的线程重新拥有锁的争夺权,

但是同时只会有一个获得锁并执行,锁释放后,其他唤醒的线程可以再次争夺资源。 那么notify和notifyall在实际效果上什么实质区别呢?

本人总觉:

1、主要的效果是notify用得不好的话,很容易导致线程的死锁

2、notify最多能唤醒一个线程,notifyAll将唤醒所有线程

直接看下面的demo吧:

import java.util.concurrent.TimeUnit;public class WaitAndNotifyTest {	public static void main(String[] args) {		Object lock = new Object();		System.out.println(lock);		for (int i = 0; i < 5; i++) {			MyThread t = new MyThread("Thread" + i, lock);			t.start();		}		try {			TimeUnit.SECONDS.sleep(2);			System.out.println("-----Main Thread notify-----");			synchronized (lock) {				//lock.notify();//最多唤醒一个线程				lock.notifyAll();//唤醒所有线程,但只有一个线程可能获得资源			}			TimeUnit.SECONDS.sleep(2);			System.out.println("Main Thread is end.");		} catch (InterruptedException e) {			e.printStackTrace();		}	}	static class MyThread extends Thread {		private String name;		private Object lock;		public MyThread(String name, Object lock) {			this.name = name;			this.lock = lock;		}		@Override		public void run() {			try {				synchronized (lock) {					System.out.println(name + " is waiting.");					lock.wait();					System.out.println(name+"----------was waked--");				}				System.out.println(name + " has been notified.");			} catch (InterruptedException e) {				e.printStackTrace();			}		}	}}分别切换注释上面的代码运行:			//lock.notify();//最多唤醒一个线程				lock.notifyAll();//唤醒所有线程,但只有一个线程可能获得资源
运行效果如下:

notify的效果

notifyAll的效果

标签: #javanotify