vir*_*iru 3 java multithreading join wait
从我在这里读到的线程加入自己 ;
当连接方法被调用时,它应该永远等待
我正在准备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 ");
}
}
Run Code Online (Sandbox Code Playgroud)
程序以下列输出结束
main about to call join
Thread-0 run started
Thread-0 run about to complete
main makeitso completed
Run Code Online (Sandbox Code Playgroud)
我错误地得到了线程永远等待的含义,还是我缺少了什么
注意:我知道,从构造开始线程不是一个推荐的做法..这是所以我只是粘贴转储确切的问题它(*不是非常确切实际上,我已经把println语句,看看该程序的流量)
Sol*_*low 10
在您的示例中没有可以连接自己的线程.
示例中的main()线程创建一个新线程,然后它加入新线程.
不要混淆Thread(即java对象)与线程(代码的执行).所有方法都属于同一个Thread对象,但它们在两个不同的线程中运行.