Java Thread join 方法可以當(dāng)前的線程暫停至你聲明的另一個(gè)線程完全結(jié)束,總共有3種重載方法。
Java Thread join
public final void join(); 這個(gè)方法會使當(dāng)前調(diào)用的線程進(jìn)行等待,直至調(diào)用的這個(gè)方法結(jié)束。如果線程被中斷會拋出InterruptedException。
public final synchronized void join(long millis); 這個(gè)方法會使當(dāng)調(diào)用的線程結(jié)束或者等待你聲明的時(shí)長。等待的時(shí)間由操作系統(tǒng)決定。并不能保證當(dāng)前的線程等待時(shí)間是確定的。
public final synchronized void join(long millis, int nanos); 同上,時(shí)間細(xì)化至毫微秒。
這面這個(gè)例子展示了Thread join 的用方法。這段代碼的主要目的是確保main線程最后一個(gè)執(zhí)行完,且第三個(gè)線程啟必須等第一個(gè)線程執(zhí)行完。
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());
}
}
上述代碼執(zhí)行完,結(jié)果如下:
Thread started:::t1
Thread started:::t2
Thread ended:::t1
Thread started:::t3
Thread ended:::t2
Thread ended:::t3
All threads are dead, exiting main thread