关于notify的问题
来源:7-2 wait方法

慕婉清9555528
2021-06-18
老师,我这里又创建了一个线程3和1一样的 同时执行,为什么线程2每次唤醒的都是线程1,都是线程1拿到锁,而没有唤醒线程3,这是不是没体现notify的随机唤醒线程???
public class Wait {
public static Object object = new Object();
static class Thread1 extends Thread {
@Override
public void run() {
synchronized (object) {
System.out.println(Thread.currentThread().getName() + "开始执行了");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程" + Thread.currentThread().getName() + "获取到了锁。");
}
}
}
static class Thread2 extends Thread {
@Override
public void run() {
synchronized (object) {
object.notify();
System.out.println("线程" + Thread.currentThread().getName() + "调用了notify()");
}
}
}
static class Thread3 extends Thread {
@Override
public void run() {
synchronized (object) {
System.out.println(Thread.currentThread().getName() + "开始执行了");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程" + Thread.currentThread().getName() + "获取到了锁。");
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
Thread3 thread3 = new Thread3();
thread1.start();
thread3.start();
Thread.sleep(200);
thread2.start();
System.out.println(thread3.getState());
}
}
写回答
1回答
-
推荐这篇文章:https://www.jianshu.com/p/99f73827c616
012021-06-22
相似问题