天天看点

Java多线程之join()方法

join()方法能让其他线程从运行状态变为阻塞状态,直到当前线程执行完成后,其他线程才会执行。

起初我对这句话理解是有误的,还好及时更正了过来。看下代码

public class Test implements Runnable {
    private String threadName;

    public Test(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println(threadName + i);
        }
    }

    public static void main(String[] args) {
        Test test1 = new Test("线程1*");
        Test test2 = new Test("线程2$");
        Thread thread1 = new Thread(test1);
        Thread thread2 = new Thread(test2);
        thread1.start();
        thread2.start();
        try {
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
           

我预想的结果是线程1先启动,然后执行一部分,线程2启动了,然后调用了join方法,此时线程1等待线程2执行完成后继续执行剩余部分。但是上面程序运行的结果是两个线程交替执行,并没有出现线程1等待线程2的情况。

我们把线程1的启动挪到线程2join方法后再看看

public class Test implements Runnable {
    private String threadName;

    public Test(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println(threadName + i);
        }
    }

    public static void main(String[] args) {
        Test test1 = new Test("线程1*");
        Test test2 = new Test("线程2$");
        Thread thread1 = new Thread(test1);
        Thread thread2 = new Thread(test2);
        thread2.start();
        try {
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread1.start();
    }
}
           

这次并没有出现线程1和线程2交替执行的情况。

所以join方法应该这么解释:

A.join()方法之后的线程(包括主线程)会等待A线程执行结束后再执行,A线程之前的线程并不会等待A执行后再执行,而是交替执行

继续阅读