package com.citi.icg.ddi.client.service.test;
import java.util.ArrayList;
import java.util.List;
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
List<SubThread> threads = new ArrayList<SubThread>();
for (int i = 0; i < 10; i++) {
SubThread thread = new SubThread(i);
threads.add(thread);
thread.start();
}
// 主線程處理其他工作,讓子線程異步去執行.
mainThreadOtherWork();
System.out.println("now waiting sub thread done.");
// 主線程其他工作完畢,等待子線程的結束, 調用join系列的方法即可(可以設置超時時間)
try {
for (Thread t : threads) {
t.join();// main 線程掛起直到目標線程t結束才恢復(thread.isAlive() return false)
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("now all done.");
}
private static void mainThreadOtherWork() {
System.out.println("main thread work start");
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main thread work done.");
}
public static class SubThread extends Thread {
int i;
public SubThread(int i) {
this.i = i;
this.setName("Thread" + i);
}
@Override
public void run() {
working();
}
private void working() {
System.out.println(i + "sub thread start working.");
busy();
System.out.println(i + "sub thread stop working.");
}
private void busy() {
try {
sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
thread-join
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
Java程序爲什麼需要調優(《大話Java性能優化》第一章第一節)
zmycoco2
2020-07-06 06:45:55
Java IO學習總結筆記-總結
Java IO 總結筆記 Java的 IO 大致可以分成 對字節流的輸入輸出, 對字符流的輸入輸出。 InputStream和OutputSt
上官云霆
2020-06-18 22:38:02
JAVA線程池ThreadPoolExecutor與阻塞隊列BlockingQueue
bincavin
2020-02-25 08:52:19
Java如何等待子線程執行結束
bincavin
2020-02-25 08:52:19
ExecutorService java線程池主線程等待子線程執行完成
bincavin
2020-02-25 08:52:19
Java中的getResourceAsStream
bincavin
2020-02-25 08:52:19
Java 程序死鎖問題原理及解決方案
zmycoco2
2020-02-22 18:51:44
《大話Java性能優化》面向對象及基礎類型相關部分
zmycoco2
2020-02-22 18:51:44
複雜JSON對象解析
上官云霆
2020-02-20 20:16:18
java.util.concurrent併發同步學習筆記
上官云霆
2020-02-20 20:16:18
Java IO學習總結筆記
上官云霆
2020-02-20 20:16:18