导读:java中join的使用 join()应该是我们在java中经常会用到的一个方法,它主要是将当前线程置为WAITTING状态,然后等待调用的线程执行完毕或被interrupted。 join()是Thread中定义的方法,我们看下他的定义: /** * Waits for this thread to die. * * p An invo
/**
* Waits for this thread to die.
*
* <p> An invocation of this method behaves in exactly the same
* way as the invocation
*
* <blockquote>
* {@linkplain #join(long) join}{@code (0)}
* </blockquote>
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/publicfinalvoidjoin()throws InterruptedException {join(0);}
06:17:14.775 [main] INFO com.flydean.JoinThread - Thread Created
06:17:14.779 [main] INFO com.flydean.JoinThread - Invoking join
06:17:14.779 [Thread-0] INFO com.flydean.JoinThread - Thread Thread-0 started
06:17:15.783 [Thread-0] INFO com.flydean.JoinThread - Thread Thread-0 exiting
06:17:15.783 [main] INFO com.flydean.JoinThread - Returned from join
06:17:15.783 [main] INFO com.flydean.JoinThread - t2 status false
@TestpublicvoidtestJoinTimeout()throws InterruptedException {
Thread t3 =newThread(newJoinThread(10));
t3.start();
t3.join(1000);
log.info("t3 status {}", t3.isAlive());}
上面的例子将会输出:
06:30:58.159 [main] INFO com.flydean.JoinThread - Thread Created
06:30:58.163 [Thread-0] INFO com.flydean.JoinThread - Thread Thread-0 started
06:30:59.172 [main] INFO com.flydean.JoinThread - t3 status true
@TestpublicvoidtestHappenBefore()throws InterruptedException {
JoinThread t4 =newJoinThread(10);
t4.start();// not guaranteed to stop even if t4 finishes.do{
log.info("inside the loop");
Thread.sleep(1000);}while( t4.processingCount >0);}