gpt4 book ai didi

java - 如果线程自身调用 join() 会发生什么

转载 作者:搜寻专家 更新时间:2023-11-01 04:05:35 25 4
gpt4 key购买 nike

从我在这里读到的Thread join on itself ;

当 join 方法被调用时,它应该永远等待

我目前正在准备 ocajp 8 认证,为此经历了转储,当我得到这个问题时,我认为主要的应该永远等待

     public class startinginconstructor extends Thread
{
private int x=2;
startinginconstructor()
{
start();
}
public static void main(String[] args) throws Exception
{
new startinginconstructor().makeitso();
}
public void makeitso() throws Exception
{
x=x-1;
System.out.println(Thread.currentThread().getName()+" about to call join ");
join();
System.out.println(Thread.currentThread().getName()+" makeitso completed ");

// above line shouldn't be executed (method shouldn't be completed as well )since it joined on itself..?

}
public void run()
{
System.out.println(Thread.currentThread().getName()+" run started ");
x*=2;
System.out.println(Thread.currentThread().getName()+" run about to complete ");
}
}

程序以下列输出结束

main about to call join
Thread-0 run started
Thread-0 run about to complete
main makeitso completed

我是不是错误地理解了线程永远等待的含义,还是我遗漏了什么

note: I know starting thread from constructor is not a recommended practice.. this is exact question in the dumps so i just pasted it (* not pretty much exact actually,i have placed println statements to see flow of the program)

最佳答案

在您的示例中没有加入自身的线程。

示例中的 main() 线程创建了一个新线程,然后它加入了新线程。

不要将 Thread(即 java 对象)与 thread(代码的执行)混淆。您的所有方法都属于同一个 Thread 对象,但它们在两个不同的线程中运行。

关于java - 如果线程自身调用 join() 会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38014063/

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