gpt4 book ai didi

Java等待线程在通知后不会恢复

转载 作者:行者123 更新时间:2023-12-01 07:19:33 24 4
gpt4 key购买 nike

我有下面的程序,有 2 个线程 T1 和 T2。 T1 首先运行并进入等待状态。 T2 正在调用通知。为什么 T1 线程不恢复并打印“Thread-0 iswake up”

public class WaitNotifyTest{
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + " is running");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is waken up");
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (this) {
try {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + " is running");
notify();
System.out.println(Thread.currentThread().getName() + " notifying");
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
});
t1.start();
t2.start();
}
}

输出为

Thread-0 is running
Thread-1 is running
Thread-1 notifying

请注意,在此输出之后我的程序不会结束/终止。谁能解释一下为什么我的程序没有终止。

最佳答案

您的代码中有两个问题1.线程之间应该使用同一个对象进行通信。2.在您已获取锁定的同一对象上调用 wait 并通知。

public class WaitNotifyTest{


public static void main(String[] args) {
Object lock=new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " is running");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is waken up");
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
try {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + " is running");
lock.notify();
System.out.println(Thread.currentThread().getName() + " notifying");
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
});
t1.start();
t2.start();
}
}

关于Java等待线程在通知后不会恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44453484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com