Java Concurrency/Threads(3)——join詳解

參考自:https://www.cnblogs.com/enjiex/p/3661551.htmlhtml

1. Java Thread join 方法做用:

將當前線程A變爲wait,執行join操做的線程B直到B結束。若是該B線程在執行中被中斷.java

2. join方法的三個重載:

public final void join();//此方法會把當前線程變爲wait,直到執行join操做的線程結束,若是該線程在執行中被中斷,則會拋出InterruptedException
public final synchronized void join(long milis); //此方法會把當前線程變爲wait,直到執行join操做的線程結束或者在執行join後等待millis的時間。由於線程調度依賴於操做系統的實現,由於這並不能保證當前線程必定會在millis時間變爲RUnnable。
public final synchronized void join(long milis, int nanos); //此方法會把當前線程變爲wait,直到執行join操做的線程結束或者在join後等待millis+nanos的時間。
package com.guoqiang;

import static com.guoqiang.ThreadColor.*;


public class Main {

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

OUT:
Thread started:::t1
Thread started:::t2
Thread ended:::t1
Thread started:::t3
Thread ended:::t2
Thread ended:::t3
All threads are dead, exiting main threadide

相關文章
相關標籤/搜索