[譯]Java Thread join示例與詳解


Java Thread join示例與詳解

Java Thread join方法用來暫停當前線程直到join操作上的線程結束。java中有三個重載的join方法:

public final void join():此方法會把當前線程變為wait,直到執行join操作的線程結束,如果該線程在執行中被中斷,則會拋出InterruptedException。

public final synchronized void join(long millis):此方法會把當前線程變為wait,直到執行join操作的線程結束或者在執行join后等待millis的時間。因為線程調度依賴於操作系統的實現,因為這並不能保證當前線程一定會在millis時間變為RUnnable。

public final synchroinzed void join(long millis, int nanos):此方法會把當前線程變為wait,直到執行join操作的線程結束或者在join后等待millis+nanos的時間。

下面的示例程序展示了Thread join方法的用法。在這段程序要保證main線程是最后一個完成的線程,同時保證第三個線程(third thread)在第一個線程(first thread)結束后才開始執行。

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 ended:::t1
Thread started:::t2
Thread started:::t3
Thread ended:::t2
Thread ended:::t3
All threads are dead, exiting main thread

 

原文鏈接:http://www.journaldev.com/1024/java-thread-join-example-with-explanation


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM