Java 多線程:join__Java

來源:互聯網
上載者:User

本文內容大多基於官方文檔和網上前輩經驗總結,經過個人實踐加以整理積累,僅供參考。

join() 方法是 java.lang.Thread 類的執行個體方法,方法簽名

public final void join() throws InterruptedException
public final void join(long millis) throws InterruptedException
public final void join(long millis, int nanos) throws InterruptedException

join() 方法使得一個線程在另一個線程結束後再執行,如果在一個線程執行個體上調用,當前啟動並執行線程將阻塞直至調用 join() 方法的線程執行個體結束

join() 方法接收 long 型別參數,使得在等待特定毫秒後線程失效

Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. 

join() 方法還可以額外接收一個 int 型別參數

Waits at most millis milliseconds plus nanos nanoseconds for this thread to die. 

樣本:

public static void main(String[] args) throws InterruptedException {    Thread t1 = new Thread(new Runnable() {        @Override        public void run() {            System.out.println("First thread started!");            System.out.println("Ready to sleep 5 seconds!");            try {                Thread.sleep(5000);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("First thread ended!");        }    });    Thread t2 = new Thread(new Runnable() {        @Override        public void run() {            System.out.println("Second thread started!");            System.out.println("Second thread ended!");        }    });    t1.start();    t1.join();    t2.start();}

如果注釋掉 t1.join();,運行結果:

去掉注釋後運行結果:

給 join() 方法傳入一個 long 型別參數,使得最長等待 3 秒

public static void main(String[] args) throws InterruptedException {    Thread t1 = new Thread(new Runnable() {        @Override        public void run() {            System.out.println("First thread started!");            System.out.println("Ready to sleep 5 seconds!");            try {                Thread.sleep(5000);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("First thread ended!");        }    });    Thread t2 = new Thread(new Runnable() {        @Override        public void run() {            System.out.println("Second thread started!");            System.out.println("Second thread ended!");        }    });    t1.start();    t1.join(3000);    t2.start();}

運行結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.