Thread.join()方法控制线程的执行顺序

Thread类join()方法重载了3次.分别是

join()throws InterruptedException;  //无参数的join()等价于join(0),作用是一直等待该线程死亡

join(long millis, int nanos) throws InterruptedException;  //最多等待该线程死亡millis毫秒

join(long millis, int nanos) throws InterruptedException ; //最多等待该线程死亡millis毫秒加nanos纳秒

join()的作用,java doc 说明:Waits for this thread to die.等待这个线程死亡,如果join的线程不死亡,程序就会阻塞在那里.

package com.qd.thread.join;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenlongbo on 2017/5/26.
 */
public class ThreadjoinTest {

    public static class RunableJob implements Runnable{
        @Override
        public void run() {
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName() + " start: " + new Date());
            try {
                TimeUnit.MILLISECONDS.sleep(2000);
                System.out.println(thread.getName() + " end: " + new Date());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
    
    public static void main(String[] args) throws InterruptedException {
        RunableJob job = new RunableJob();
        Thread t1 = new Thread(job,"T1");
        Thread t2 = new Thread(job,"T2");
        Thread t3 = new Thread(job,"T3");
        Thread t4 = new Thread(job,"T4");
        Thread t5 = new Thread(job,"T5");
        t4.start();
        t4.join();
        t5.start();
        t5.join();
        t3.start();
        t3.join();
        t2.start();
        t2.join();
        t1.start();
    }


}

 

程序的执行结果:

T4 start: Fri May 26 17:20:29 CST 2017
T4 end: Fri May 26 17:20:31 CST 2017
T5 start: Fri May 26 17:20:31 CST 2017
T5 end: Fri May 26 17:20:33 CST 2017
T3 start: Fri May 26 17:20:33 CST 2017
T3 end: Fri May 26 17:20:35 CST 2017
T2 start: Fri May 26 17:20:35 CST 2017
T2 end: Fri May 26 17:20:37 CST 2017
T1 start: Fri May 26 17:20:37 CST 2017
T1 end: Fri May 26 17:20:39 CST 2017

Process finished with exit code 0

转载于:https://www.cnblogs.com/cbySense/p/6909619.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值