gpt4 book ai didi

java - 等待和通知 - 打印不同的线程 ID

转载 作者:行者123 更新时间:2023-12-01 16:15:30 25 4
gpt4 key购买 nike

抱歉,如果这是一个基本问题。我是线程新手。我试图理解 wait() 和 notification() 线程。问题是当我在同一个类上等待和通知时,线程 ID 的打印方式不同。是的,通知正常发生,但我想知道为什么通知线程 ID 不断变化?请阐明一下,等待和通知应该发生在同一个线程中,不是吗?

等待线程:

import java.util.concurrent.CompletableFuture;

public class ThreadWait implements Runnable {

private static ThreadWait threadWait;
private ThreadNotify threadNotify = ThreadNotify.getInstance();

private ThreadWait() {
}

public static ThreadWait getInstance() {
if (threadWait == null) {
threadWait = new ThreadWait();
}

return threadWait;
}

@Override
public void run() {
synchronized (this) {
try {
for (int i = 0; i < 5; i++) {

Thread.sleep(2000);

CompletableFuture.runAsync(() -> {
// method call in async.
threadNotify.notifyThread();
});


System.out.println(Thread.currentThread().getId() + "=======ThreadWait : wait========");
wait();

}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void notifyThread() {
synchronized (this) {
System.out.println(Thread.currentThread().getId() + "=======ThreadWait : Notified========");
notify();
}
}
}

通知线程

public class ThreadNotify {

private static ThreadNotify threadNotify;
private ThreadWait threadWait;

private ThreadNotify(){}

public static ThreadNotify getInstance(){
if(threadNotify == null){
threadNotify = new ThreadNotify();
}

return threadNotify;
}

public void notifyThread(){

threadWait = ThreadWait.getInstance();
fibonacci(44);
//threadWait.notify()
threadWait.notifyThread(); // want to print threadIDs, so created this method.
}

private int fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}

}

主线程:

public class MainThread {
public static void main(String[] args) {

ThreadWait wait = ThreadWait.getInstance();

Thread th = new Thread(wait);
th.start();
}
}

输出:

12=======ThreadWait : wait========
14=======ThreadWait : Notified========
12=======ThreadWait : wait========
15=======ThreadWait : Notified========
12=======ThreadWait : wait========
16=======ThreadWait : Notified========
12=======ThreadWait : wait========
17=======ThreadWait : Notified========
12=======ThreadWait : wait========
18=======ThreadWait : Notified========

最佳答案

如果您在主类中看到代码ThreadWait wait = ThreadWait.getInstance();,您正在创建一个实例并将其交给等待线程。它使用单例模式来创建实例。但是对于通知,您使用的是 CompletableFuture 它创建了一个单独的线程

关于java - 等待和通知 - 打印不同的线程 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62402303/

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