Java Thread Join

英文原文:Java Thread Join Example

Java Thread join 方法可以当前的线程暂停至你声明的另一个线程完全结束,总共有3种重载方法。

Java Thread join

public final void join(); 这个方法会使当前调用的线程进行等待,直至调用的这个方法结束。如果线程被中断会抛出InterruptedException。

public final synchronized void join(long millis); 这个方法会使当调用的线程结束或者等待你声明的时长。等待的时间由操作系统决定。并不能保证当前的线程等待时间是确定的。

public final synchronized void join(long millis, int nanos); 同上,时间细化至毫微秒。

这面这个例子展示了Thread join 的用方法。这段代码的主要目的是确保main线程最后一个执行完,且第三个线程启必须等第一个线程执行完。

package com.journaldev.threads;

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();

        //start second thread after waiting for 2 seconds or if it's dead
        try {
            t1.join(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t2.start();

        //start third thread only when first thread is dead
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t3.start();

        //let all threads finish execution before finishing main thread
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("All threads are dead, exiting main thread");
    }

}

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
All threads are dead, exiting main thread

你可能感兴趣的:(Java Thread Join)