您好,登錄后才能下訂單哦!
這篇文章主要介紹了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父線程等待所有子線程退出的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學習!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。