线程连接自身 [英] Thread join on itself
问题描述
我怀疑,线程加入时会发生什么。即线程自己调用join方法。我没有收到任何错误。
I am in doubt, what happens when a thread joins itself. i.e thread calls the join method on its own. I am not getting any error.
示例:
public class JoinItself extends Thread {
public void run() {
System.out.println("Inside the run method ");
System.out.println(Thread.currentThread().isAlive());
for(int i=0;i<5;i++) {
try {
System.out.println("Joining itself ...");
Thread.currentThread().join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JoinItself j = new JoinItself();
System.out.println(j.isAlive());
j.start();
System.out.println(j.isAlive());
System.out.println("Thread started ...");
}
}
但为什么?我应该收到任何错误吗?
But Why? Should I get any error?
推荐答案
线程加入的概念没有意义。
The concept of a thread joining itself does not make sense.
碰巧是 join()
方法使用 isAlive()
方法来确定
从 join()
方法返回。在当前的实现中,它还
不检查线程是否正在加入自己。
换句话说, join()
当且仅当线程不再存在时,>方法返回。这将产生
永远等待的效果。
It happens out that the join()
method uses the isAlive()
method to
determine when to return from the join()
method. In the current implementation, it also
does not check to see if the thread is joining itself.
In other words, the join()
method returns when and only when the thread is no longer alive. This will have the effect of
waiting forever.
这篇关于线程连接自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!