Thread.join

__HelloWorld__發表於2018-08-30

Waits for this thread to die

確保執行緒先後順序執行

public class ThreadJoinTest {
    public static void main(String[] args) throws Exception {
        Thread thread0 = new Thread(() -> System.out.println("a is running"));
        Thread thread1 = new Thread(() -> System.out.println("b is running"));
        Thread thread2 = new Thread(() -> System.out.println("c is running"));
        Thread thread3 = new Thread(() -> System.out.println("d is running"));
        thread0.start();
        thread0.join();

        thread1.start();
        thread1.join();

        thread2.start();
        thread2.join();

        thread3.start();
        thread3.join();
        System.out.println("done");
    }
}

執行結果

a is running
b is running
c is running
d is running
done