java join 方法的使用

來源:互聯網
上載者:User

標籤:test   tar   star   pac   com   ati   over   col   str   

在很多情況下,主線程建立並啟動子線程,如果子線程中要進行大量的耗時運算,主線程往往將早於子線程結束之前結束。這時,如果主線程想等待子線程執行完成之後再結束,比如子線程處理一個資料,主線程要取得這個資料中的值,就要用到join()方法了,方法join()的作用是等待線程對象被銷毀。

 

程式碼範例:

package com.test;public class TestJoin extends Thread {    @Override    public void run() {        try {            int secondValue = (int)(Math.random() * 10000);            System.out.println(secondValue);            Thread.sleep(secondValue);        } catch (Exception e) {            e.printStackTrace();        }    }}
package com.test;public class Run {        public static void main(String[] args) {                try {            TestJoin join = new TestJoin();            join.start();            join.join();            System.out.println("我想當線程對象執行完畢後我再執行");                        } catch (Exception e) {            e.printStackTrace();        }    }}
運行結果:7694我相當線程對象執行完畢後我再執行

ps:如果把Run.java中的join.join()方法注釋掉, 則會先列印 “我想當線程對象執行完畢後我再執行”

方法join與異常:

  在join過程中,如果當前線程對象被中斷,則當前線程出現異常。

join(long)中的參數是設定等待時間。

方法join(long)與sleep(long)的區別:

  方法join(long)的功能個在內部是使用wait(long)方法來實現的,所以join(long)方法具有釋放鎖的特點。而Thread.sleep(long)方法卻不釋放鎖.

java join 方法的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.