標籤: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 方法的使用