Thread.join(100)未等待工作线程完成,为何不抛出运行时异常?
Thread.join(long) 未告知工作线程仍运行的原因
示例代码
public static void main(String [] argv){ Logger l = LoggerFactory.getLogger( "MAIN" ); Thread thread = new Thread(()->{ Logger ll = LoggerFactory.getLogger( "WRKR" ); ll.debug("start t1"); try { Thread.sleep( 10000 ); } catch (InterruptedException e) { throw new RuntimeException( e ); } ll.debug("end t1"); }) ; l.info("main"); thread.start(); try { Thread.sleep( 8000 ); } catch (InterruptedException e) { throw new RuntimeException( e ); } try { l.info("trying to join"); thread.join(100); l.info("joined"); } catch (InterruptedException e) { throw new RuntimeException( e ); } l.info("end main"); }
运行输出
10:57:38.871 [main] INFO MAIN - main 10:57:38.879 [Thread-0] DEBUG WRKR - start t1 10:57:46.884 [main] INFO MAIN - trying to join 10:57:46.993 [main] INFO MAIN - joined 10:57:46.993 [main] INFO MAIN - end main 10:57:48.880 [Thread-0] DEBUG WRKR - end t1
问题解析
Thread.join(long timeout)的设计逻辑并非你预期的那样,它不会因为目标线程未结束就抛出异常。这个方法的核心行为是:让当前线程进入等待状态,直到两个条件满足其一就返回:
- 目标线程在超时时间内执行完毕;
- 等待时长达到设定的
timeout值,无论目标线程是否还在运行。
如果需要确认目标线程在join后是否仍在运行,你需要主动调用thread.isAlive()方法进行判断,示例代码如下:
try { l.info("trying to join"); thread.join(100); if (thread.isAlive()) { l.info("Worker thread is still running"); } else { l.info("Worker thread has finished"); } l.info("joined"); } catch (InterruptedException e) { throw new RuntimeException( e ); }
Thread.join(long)仅会在等待过程中被其他线程中断时抛出InterruptedException,这也是你代码中已经捕获的异常类型,它不会因为目标线程未结束而抛出运行时异常。
内容的提问来源于stack exchange,提问作者DDS
相关产品推荐
相关产品推荐

