请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

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

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

  • 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 01:45:52

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

0 回复 有任何疑惑可以回复我~
  • 提问者 jing9202 #1
    谢谢老师,确实需要多调用几次notify()才能看到效果
    回复 有任何疑惑可以回复我~ 2019-11-01 15:59:17
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信