谁先进入等待池,notify就先唤醒谁,并不是随机唤醒???

来源:8-7 notify和notifyall的区别

jing9202

2019-10-31

翔仔老师你好!
这是我的代码:
/**
*

  • notify与notifyAll的区别

*/
public class NotifyDemo {
private boolean isGo = false;

public static void main(String[] args) {
	NotifyDemo notifyDemo = new NotifyDemo();
	Runnable waitRunn = new Runnable() {

		@Override
		public void run() {
			notifyDemo.waitTask();
			System.out.println(Thread.currentThread().getName() + ",执行完毕");
		}
	};
	Runnable notifyRunn = new Runnable() {

		@Override
		public void run() {
			notifyDemo.notifyTask();
		}
	};
	Thread t1 = new Thread(waitRunn, "线程1");
	Thread t2 = new Thread(waitRunn, "线程2");
	Thread t3 = new Thread(waitRunn, "线程3");
	Thread t4 = new Thread(waitRunn, "线程4");
	Thread t5 = new Thread(waitRunn, "线程5");
	Thread t6 = new Thread(waitRunn, "线程6");

	Thread tNotify = new Thread(notifyRunn, "线程notify");

	t1.start();
	t2.start();
	t3.start();
	t4.start();
	t5.start();
	t6.start();
	
	try {
		Thread.sleep(2000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	tNotify.start();
}

private synchronized void waitTask() {
	while (!isGo) {
		try {
			System.out.println(Thread.currentThread().getName() + ",进入等待池");
			wait();
			System.out.println(Thread.currentThread().getName() + ",被唤醒");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

private synchronized void notifyTask() {
	while (!isGo) {
		isGo = true;
		 System.out.println("随机唤醒一个线程并让它进入锁池");
		 notify();
		// System.out.println("唤醒全部线程并让它们进入锁池");
		// notifyAll();
	}
}

}
我执行了以上代码几十次,每次先进入等待池的线程,都会被notify唤醒,而没有出现随机唤醒的情况。这是什么原因导致的呢?
console打印结果:
图片描述

写回答

1回答

翔仔

2019-11-01

同学好,由于线程数太少,看不出随机性,可以写几十个线程,然后在一次执行里,多调用几次notify() 就会发现notify并不会按照 1,2,3,4,5,6.。。这样的顺序去唤醒线程

0
1
jing9202
谢谢老师,确实需要多调用几次notify()才能看到效果
2019-11-01
共1条回复

剑指Java面试-Offer直通车 百度资深面试官授课

招聘季即将到来,让百度资深面试官来为你的高薪Offer保驾护航

8427 学习 · 1870 问题

查看课程