线程合并

发布时间 2023-12-02 15:37:43作者: 林浅

主要来说就是主线程等待子线程 可以设置参数(1000)就是等待子线程一秒 如果子线程中要执行3秒 则还是主线程先执行完

package org.example.test1;

import java.util.concurrent.TimeUnit;

public class JoinThread {
    static int value = 1;

    public static void main(String[] args) throws InterruptedException {
        Thread T1 = new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            value = 10;
            System.out.println("线程Runnable");
        });
    T1.start();//异步
    Thread.sleep(1000);
    T1.join(); //异步变成同步(子线程会等待主线程结束)
    System.out.println("主线程:"+value);
    }
}