理解高并发(11).线程通信之_join使用及原理

来源:互联网 发布:ubuntu怎么删除目录 编辑:程序博客网 时间:2024/06/08 06:53
概述
根据jdk官方API的定义:
Thread.join方法是阻塞调用线程(也称阻塞主线程),待被调用线程(子线程)运行结束后主线程才会被唤醒。 通常用在main方法中。

替代方案
jdk1.7 CountDownLatch

join底层实现原理
wait、notify机制,可以深入的查看底层实现源码:
/** 2 * Waits at most <code>millis</code> milliseconds for this thread to3* die. A timeout of <code>0</code> means to wait forever.4*/ 5//此处A timeout of 0 means to wait forever 字面意思是永远等待,其实是等到t结束后。 6 publicfinalsynchronizedvoid join(long millis) throws InterruptedException { 7 long base = System.currentTimeMillis(); 8 long now = 0; 9 10if (millis < 0) {11thrownew IllegalArgumentException("timeout value is negative");12 }1314if (millis == 0) {15while (isAlive()) {16 wait(0);17 }18 } else {19while (isAlive()) {20long delay = millis - now;21if (delay <= 0) {22break;23 }24 wait(delay);25 now = System.currentTimeMillis() - base;26 }27 }28 }

原创粉丝点击