多线程系列08-join()

2019-07-22  本文已影响0人  Sandy_678f

join() 的作用:让“主线程”等待“子线程”结束之后才能继续运行。
join()源码示例:

public final void join() throws InterruptedException {
    join(0);
}

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) {
        while (isAlive()) {
            wait(0);
        }
    } else {
        while (isAlive()) {
            long delay = millis - now;
            if (delay <= 0) {
                break;
            }
            wait(delay);
            now = System.currentTimeMillis() - base;
        }
    }
}

源码分析:
(01) 当millis==0时,会进入while(isAlive())循环;即只要子线程是活的,主线程就不停的等待。
(02) isAlive()应该是判断“子线程s”是不是Alive状态,而wait(0)的作用是让“当前线程”等待,而这里的“当前线程”是指当前在CPU上运行的线程。所以,虽然是调用子线程的wait()方法,但是它是通过“主线程”去调用的;所以,休眠的是主线程,而不是“子线程”!

示例:

public class JoinTest {

    static class ThreadD extends Thread{

        public ThreadD(String name){
            super(name);
        }

        public void run(){

            System.out.printf("%s start\n", this.getName());
            //延时操作
            for(int i=0; i<100000; i++)
                ;
            System.out.printf("%s finish\n", this.getName());
        }
    }

    public static void main(String[] args) {

        try{
            ThreadD t1 = new ThreadD("t1");

            t1.start();
            t1.join();
            System.out.printf("%s finish\n", Thread.currentThread().getName());

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

运行结果:

t1 start
t1 finish
main finish
上一篇下一篇

猜你喜欢

热点阅读