• 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

  • 相关阅读:
    redis主从同步
    redis持久化
    redis发布订阅
    mariadb主从复制,
    nginx+uwsgi+django+virtualenv+supervisor发布web服务器
    Oracle 11gR2 RAC Installation on Oracle Linux 6.5
    ORA-1555 causes and solutions
    Linux实时查看日志的四种命令详解
    Linux查看日志常用命令
    oracle 11g 静默安装
  • 原文地址:https://www.cnblogs.com/cbySense/p/6909619.html
Copyright © 2020-2023  润新知