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