Java线程之join

简述

Thread类的join方法用来使main线程进入阻塞状态,进而等待调用join方法的线程执行,join有三个重载方法:

public final void join()
使主线程进入阻塞状态,直到调用join的线程执行完成,如果线程被中断将抛出InterruptedException异常

public final synchronized void join(long millis):
使主线程最多阻塞指定时间(毫秒)

public final synchronized void join(long millis, int nanos)
使主线程最多阻塞指定时间(毫秒),可以精确到纳秒

实例

主线程等待所有子线程先执行完成

package com.lkf.mulithread;

public class ThreadJoinExample {
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable(), "线程t1");
        Thread t2 = new Thread(new MyRunnable(), "线程t2");
        Thread t3 = new Thread(new MyRunnable(), "线程t3");

        t1.start();

        //两秒钟以后启动第二个线程
        try {
            t1.join(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t2.start();

        //第一个线程完成之后启动第三个线程
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t3.start();

        //三个子线程先执行完,然后继续主线程
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("所有线程执行完毕");
    }

}

class MyRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("Thread started:::" + Thread.currentThread().getName());
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread ended:::" + Thread.currentThread().getName());
    }
}

结果:

Thread started:::线程t1
Thread started:::线程t2
Thread ended:::线程t1
Thread started:::线程t3
Thread ended:::线程t2
Thread ended:::线程t3
所有线程执行完毕
posted @ 2018-03-22 21:35  IT码客  阅读(139)  评论(0编辑  收藏  举报