java多线程– join(线程插队,优先执行)

java
Author

dd21

Published

December 5, 2022

package cn.usts.edu.lesson06;

/**
 * 使用join方法
 * 测试再main主线程执行的过程中  强行插入B线程
 *
 * 测试结果是 main线程执行过程中,添加B线程,等待B线程执行完毕后,main线程接着执行
 * 
 * 一定要是这个顺序,
 * thread.start();
 * thread.join();
 * 注意start()和join的位置.很关键
 * */

public class ThreadJoinDemo implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+i);
        }

    }

    public static void main(String[] args) throws InterruptedException {
        ThreadJoinDemo threadJoinDemo = new ThreadJoinDemo();
        Thread thread = new Thread(threadJoinDemo,"B线程");

        for (int i = 0; i < 200; i++) {
            if (i==100){
                    thread.start();// 线程启动
                    thread.join();// 线程加入,main线程阻塞.等待B线程执行结束
            }
            System.out.println("main线程"+i);
        }
    }
}