谁先进入等待池,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回答
-
同学好,由于线程数太少,看不出随机性,可以写几十个线程,然后在一次执行里,多调用几次notify() 就会发现notify并不会按照 1,2,3,4,5,6.。。这样的顺序去唤醒线程
012019-11-01
相似问题