java 多线程 Thread join

Thread.join()

    public static void joinTest1() throws InterruptedException {
        System.out.println("start");
        Thread t = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();

        //Waits for this thread to die. 线程t加入当前main线程,等待线程t死亡才继续执行main线程
        t.join();//等待任务线程执行完,main线程才继续往下执行

        System.out.println("end");
    }



输出:
start
Thread-0
end

 

Thread.join(long millis)

    public static void joinTest2() throws InterruptedException {
        System.out.println("start");
        Thread t = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();

        //Waits at most milliseconds for this thread to die.
        t.join(1000);//任务线程join 1秒后,main线程继续执行,任务线程需要执行3秒,所以join 的1秒过后 任务线程还要完成执行任务

        System.out.println("end");
    }


输出:
start
end
Thread-0



    public static void joinTest3() throws InterruptedException {
        System.out.println("start");
        Thread t = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();

        t.join(4000);//任务线程join 4秒后,main线程继续执行,任务线程消耗3秒,索引join 4秒时,任务线程已经执行完3秒任务

        System.out.println("end");
    }



输出:
start
Thread-0
end

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值