Java父線程(或是主線程)等待所有子線程退出的實例
更新時間:2017年11月24日 09:12:00 作者:牛孝祖
下面小編就為大家分享一篇Java父線程(或是主線程)等待所有子線程退出的實例,具有很好的參考價值,希望對大家有所幫助
實例如下:
static void testLock1(){
final AtomicInteger waitCount = new AtomicInteger(30000);
final Object waitObj = new Object();
System.out.println("start"+System.currentTimeMillis());
for (int i=0;i<30000;i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
waitCount.decrementAndGet();
synchronized(waitObj){
waitObj.notifyAll();
}
}
}).start();
}
while( waitCount.intValue()>0) {
synchronized (waitObj) {
if(waitCount.intValue()>0){
try {
waitObj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
System.out.println("ok"+System.currentTimeMillis());
}
static void testLock2(){
final CountDownLatch workLauch = new CountDownLatch(30000);//計數(shù)器
System.out.println("start2"+System.currentTimeMillis());
for (int i=0;i<30000;i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
workLauch.countDown();
}
}).start();
}
try {
workLauch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ok2"+System.currentTimeMillis());
}
public static void main(String[] args) {
testLock1();
testLock2();
}
第一種是我隨便寫的實現(xiàn),有點糙。第二種是朋友告知的一個類,java的concurrent中的,據(jù)說還有幾個相似功能的類實現(xiàn)。這30000個線程 時間差大概是不到200ms的樣子
以上這篇Java父線程(或是主線程)等待所有子線程退出的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
java8時間 yyyyMMddHHmmss格式轉(zhuǎn)為日期的代碼
這篇文章主要介紹了java8時間 yyyyMMddHHmmss格式轉(zhuǎn)為日期的代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
Java SSM整合開發(fā)統(tǒng)一結(jié)果封裝詳解
這篇文章主要介紹了Java SSM整合開發(fā)實現(xiàn)統(tǒng)一結(jié)果封裝,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
Java 實現(xiàn)Redis存儲復(fù)雜json格式數(shù)據(jù)并返回給前端
這篇文章主要介紹了Java 實現(xiàn)Redis存儲復(fù)雜json格式數(shù)據(jù)并返回給前端操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
SpringBootWeb?入門了解?Swagger?的具體使用
這篇文章主要介紹了SpringBootWeb?入門了解?Swagger?的具體使用,Swagger?框架可以根據(jù)已經(jīng)實現(xiàn)的方法或者類,通過頁面的方式直觀清晰的查看或者進行測試該方法,需要的朋友可以參考下2024-08-08

