class ThreadA extends Thread { public int num = 0; public void run() { synchronized (this) { for (int i = 0; i < 3; ++i) this.num += i; // notifyAll(); } } public int getNum() { return this.num; } } public class TestNotify extends Thread { public static void main(String[] args) { ThreadA threada = new ThreadA(); threada.start(); synchronized (threada){ try { threada.wait(); System.out.println("我还是执行了"); }catch (InterruptedException e){ e.printStackTrace(); } } System.out.println(threada.getNum()); } }为什么主线程没有被唤醒取依然执行了
时间: 2024-02-14 13:21:31 浏览: 19
在主线程中,我们使用了`wait()`方法来等待`ThreadA`线程的通知。但是,在`ThreadA`线程中,我们没有调用`notify()`或`notifyAll()`方法来唤醒等待的线程。因此,主线程一直处于等待状态,直到程序结束。
如果将`notifyAll()`方法取消注释,那么主线程会被唤醒并继续执行。
相关问题
class ThreadA extends Thread { public int num = 0; public void run() { synchronized (this) { for (int i = 0; i < 3; ++i) this.num += i; // notifyAll(); } } public int getNum() { return this.num; } } public class TestNotify extends Thread { public static void main(String[] args) { ThreadA threada = new ThreadA(); threada.start(); synchronized (threada){ try { threada.wait(); System.out.println("我还是执行了"); }catch (InterruptedException e){ e.printStackTrace(); } } System.out.println(threada.getNum()); } }为什么“我还是执行了”能被输出
在`ThreadA`线程中,我们使用了`synchronized`关键字来锁住对象,并在其中进行了运算,但是没有调用`notify()`或`notifyAll()`方法唤醒其他等待该对象锁的线程。
在主线程中,我们使用`synchronized`关键字锁住了`ThreadA`对象,并调用了`wait()`方法等待该对象的锁。当`ThreadA`线程执行完同步块中的运算后,释放了该对象锁,主线程获得了该对象锁并继续执行,输出了“我还是执行了”。
这里需要注意的是,主线程获得了`ThreadA`对象锁后,才能输出“我还是执行了”。如果`ThreadA`线程在主线程调用`wait()`方法前就已经执行完同步块并释放了锁,那么主线程就无法等待`ThreadA`线程的通知,也就无法输出“我还是执行了”。
class ThreadA2 extends Thread { public int num = 0; public void run() { System.out.println(getName()); synchronized (this) { for (int i = 0; i < 3; ++i) this.num += i; } } public int getNum() { return this.num; } } public class TestNotify2 extends Thread { public static void main(String[] args) { ThreadA2 thread = new ThreadA2(); thread.start(); synchronized (thread){ try { thread.wait(); }catch (InterruptedException e){ e.printStackTrace(); } } } }代码为什么主线程没有被通知确还是执行了
在主线程中使用了 `wait()` 方法,这会使主线程进入等待状态,并释放对 `thread` 对象的锁。当 `thread` 对象调用 `notify()` 方法时,会通知正在等待 `thread` 对象锁的线程(即主线程)继续执行,但是在此之前,`thread` 对象的锁已经被释放,所以主线程并没有被通知而继续执行了。要想主线程能够被通知到,可以在主线程中使用一个标志位来判断是否被通知,或者使用 `notifyAll()` 方法来通知所有等待的线程。