java 线程连接本身

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5999595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:55:34  来源:igfitidea点击:

Thread join on itself

javamultithreadingjoin

提问by Aika

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.

我很怀疑,当一个线程加入自己时会发生什么。即线程自己调用 join 方法。我没有收到任何错误。

Sample :

样本 :

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?

但为什么?我应该得到任何错误吗?

采纳答案by sgokhales

The concept of a thread joining itself does not make sense.

线程连接本身的概念没有意义。

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.

碰巧该join()方法使用该isAlive()方法来确定何时从该join()方法返回。在当前的实现中,它也不检查线程是否正在加入自身。
换句话说,join()当且仅当线程不再活动时,该方法才返回。这将产生永远等待的效果。

回答by Stephen C

Should I get any error ?

我应该得到任何错误吗?

I wouldn't expect an error. The javadocsfor Thread.join()do not say that this is an error, and it is just conceivable that some crazy person may use this as another way of doing a sleep, so an undocumented error would be a bad idea.

我不希望出现错误。的javadocsforThread.join()并没有说这是一个错误,并且可以想象一些疯狂的人可能会使用它作为执行 a 的另一种方式sleep,因此未记录的错误将是一个坏主意。

I guess that Sun didn't think this was a case that was worth giving special attention to.

我想,Sun 并不认为这是一个值得特别关注的案例。

回答by bina ramani

The join waits for notification from the other thread. In this case same thread is waiting for itself to notify and hence no notification is received. The program will never end.

加入等待来自其他线程的通知。在这种情况下,同一个线程正在等待自己通知,因此没有收到通知。该计划永远不会结束。