gpt4 book ai didi

java - 在java中加入线程

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:55:10 26 4
gpt4 key购买 nike

(Thread) A.join() - 导致当前线程等待线程 A 完成。我当时认为从 run 方法调用 this.join() 会导致线程死锁 - 它会等待自己完成。然而它并没有发生——代码编译和运行得很好——没有死锁。当我调用 this.join() 时会发生什么?

最佳答案

OP 在提供的示例中使用 this.join()

Nathan 在他的示例中使用了 Thread.currentThread().join()。

通过使用 this.join() 创建一个正在加入的新线程,但主线程是完整的。

@内森以下按预期工作:

public class Main extends Thread {

@Override
public synchronized void run() {
super.run();
try {
this.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
new Main().start();
System.out.println("hello");
}
}

关于java - 在java中加入线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8138173/

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