首页 > 代码库 > java基础知识回顾之java Thread类学习(十一)--join方法的理解

java基础知识回顾之java Thread类学习(十一)--join方法的理解



以下面例子说明下面的源码:main 线程 和 A线程,A线程是main线程创建并且启动的,main线程优先级比较高,正在执行;
这个时候main线程调用A.join()之后,main线程一直等待,直到A线程运行完毕,main线程才运行。

join方法的源码:      

* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever. * * <p> This implementation uses a loop of {@code this.wait} calls * conditioned on {@code this.isAlive}. As a thread terminates the * {@code this.notifyAll} method is invoked. It is recommended that * applications not use {@code wait}, {@code notify}, or * {@code notifyAll} on {@code Thread} instances. * * @param millis * the time to wait in milliseconds * * @throws IllegalArgumentException * if the value of {@code millis} is negative * * @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.
*/
// 加锁当前线程
public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) {
//A线程是start,在运行中 while (isAlive()) {
          //main线程等待 wait(0); } } else {
//join(timeOut)的情况 while (isAlive()) {
          //根据当前timeout的时间-now 是否<=0进行判断,主线程是否继续阻塞等待 long delay = millis - now;
//等待超时时间到了,则主线程不阻塞了,等待结束 if (delay <= 0) { break; } wait(delay);
//子线程从循环开始到现在运行的时间 now = System.currentTimeMillis() - base; } } }

给一个例子来理解:

package concurrentMy.joins;/** *  * @author Administrator *  * main 线程 和 A线程,A线程是main线程创建并且启动的,main线程优先级比较高,正在执行; * 这个时候main线程调用A.join()之后,main线程一直等待,直到A线程运行完毕,main线程才运行 *  */class ThreadA extends Thread {        public ThreadA(String name){        super(name);    }    @Override    public void run() {               for (int i = 0; i < 20; i++) {            // 复写父类的toString方法, 返回该线程的字符串表示形式,包括线程名称、优先级和线程组。            System.out.println(Thread.currentThread().getName() + "-" + i);        }    }}public class JoinDemo {    /**     * @param args     * @throws InterruptedException      */    public static void main(String[] args) throws InterruptedException {        ThreadA A = new ThreadA("线程A");        A.start();        A.join(); //A线程加入到“main线程”中,main线程一直等待,直到A线程执行完毕,main线程才运行        System.out.println(Thread.currentThread().getName() + "执行");        System.out.println(Thread.currentThread().getName() + "执行终止");    }}

 输出结果:

线程A-0线程A-1线程A-2线程A-3线程A-4线程A-5线程A-6线程A-7线程A-8线程A-9线程A-10线程A-11线程A-12线程A-13线程A-14线程A-15线程A-16线程A-17线程A-18线程A-19main执行main执行终止  

代码运行整个过程说明入下图:

 

技术分享

 

 

java基础知识回顾之java Thread类学习(十一)--join方法的理解