简体   繁体   English

Thread.join()(实例方法)

[英]Thread.join() (instance method)

Why is it not possible to .join() before starting a thread? 为什么在启动线程之前无法.join() Should not be implicit that if I call join() on a thread even if not started previously should be started? 不应该隐含的是,即使我之前未启动,如果我在线程上调用join(),也应该启动吗?

Because join() waits for a thread to die as the Javadoc say; 正如Javadoc所说,因为join()等待线程死亡。 it cannot die if it hasn't started yet. 如果还没有开始,它就不会死。

I do not think it should start a thread if it is not started because the method would do two things: start a thread and wait for the thread, which is bad design. 我不认为如果不启动它就不应启动线程,因为该方法会做两件事:启动线程并等待线程,这是不好的设计。

Acorrding to javadoc 根据javadoc

The join method allows one thread to wait for the completion of another. join方法允许一个线程等待另一个线程的完成。 If t is a Thread object whose thread is currently executing, 如果t是当前正在执行线程的Thread对象,

t.join();

causes the current thread to pause execution until t's thread terminates. 导致当前线程暂停执行,直到t的线程终止。 Overloads of join allow the programmer to specify a waiting period. 连接的重载使程序员可以指定等待时间。

SO it clearly tells that if you join a thread then the current thread will wait until the termination of thread. 因此,它清楚地表明,如果您加入一个线程,那么当前线程将等到线程终止。 So if a thread is not started yet how can it be terminated. 因此,如果尚未启动线程,如何终止它。

Proof By Contradiction :D 矛盾证明:D

say you can join a thread t without starting. 说您可以不启动就加入线程t then you call 然后你打电话

t.join();

now as per the behavior of join current thread will be waiting. 现在,根据加入行为,当前线程将处于等待状态。 Now say some evil thinking (!) comes to your mind and you haven't started the thread (:D). 现在说您想到了一些邪恶的想法(!),而您还没有启动线程(:D)。 What will be happened now? 现在会发生什么? Imagine this scenario and you will find your answer 想象一下这种情况,您将找到答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM