Java父線程(或是主線程)等待所有子線程退出的實(shí)例
實(shí)例如下:
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);//計(jì)數(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(); }
第一種是我隨便寫的實(shí)現(xiàn),有點(diǎn)糙。第二種是朋友告知的一個(gè)類,java的concurrent中的,據(jù)說還有幾個(gè)相似功能的類實(shí)現(xiàn)。這30000個(gè)線程 時(shí)間差大概是不到200ms的樣子
以上這篇Java父線程(或是主線程)等待所有子線程退出的實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java8時(shí)間 yyyyMMddHHmmss格式轉(zhuǎn)為日期的代碼
這篇文章主要介紹了java8時(shí)間 yyyyMMddHHmmss格式轉(zhuǎn)為日期的代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-09-09Java SSM整合開發(fā)統(tǒng)一結(jié)果封裝詳解
這篇文章主要介紹了Java SSM整合開發(fā)實(shí)現(xiàn)統(tǒng)一結(jié)果封裝,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08Java 實(shí)現(xiàn)Redis存儲(chǔ)復(fù)雜json格式數(shù)據(jù)并返回給前端
這篇文章主要介紹了Java 實(shí)現(xiàn)Redis存儲(chǔ)復(fù)雜json格式數(shù)據(jù)并返回給前端操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07淺談Java基礎(chǔ)知識(shí)之BigDecimal
我們又來回顧Java基礎(chǔ)知識(shí)啦,今天講的是BigDecimal的基本使用以及異常處理,下文中有非常詳細(xì)的代碼示例以及注釋哦,需要的朋友可以參考下2021-05-05SpringBootWeb?入門了解?Swagger?的具體使用
這篇文章主要介紹了SpringBootWeb?入門了解?Swagger?的具體使用,Swagger?框架可以根據(jù)已經(jīng)實(shí)現(xiàn)的方法或者類,通過頁面的方式直觀清晰的查看或者進(jìn)行測試該方法,需要的朋友可以參考下2024-08-08