翔仔老师你好!
这是我的代码:
/**
*
*/
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打印结果:
登录后可查看更多问答,登录/注册