线程强制执行 - join

HeJin小于 1 分钟Java多线程详解

Join合并线程,待此线程执行完成后,在执行其他线程,其他线程阻塞。

可以想象成插队

public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("线程vip来了==>" +i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 启动我们的线程
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);

        // 主线程
        for (int i = 0; i < 200; i++) {
            if (i == 100){
                // 插队
                thread.start();
                thread.join();
            }
            System.out.println("main-" + i);
        }
    }
}