zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    java 重定向和转发的区别
    Python练习100则--部分概念的没有做
    MYSQL忘记root密码后如何修改
    二分查找注意点
    数据库连接串整理
    MYSQL mysqldump数据导出详解
    MVCC的一些理解
    MySQL 加锁处理分析-转载
    扩展1
    maven-windows使用
  • 原文地址:https://www.cnblogs.com/cbySense/p/6909619.html
Copyright © 2011-2022 走看看