天天看點

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執行後再執行,而是交替執行

繼續閱讀