實例如下:
靜態void testlock1(){final atomicInteger waitcount = new atomicInteger(30000);最終對象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) } })。開始(); } while(waitcount.intvalue()> 0){同步(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); //計數器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(e.printstacktrace() }嘗試{worklauch.await(); } catch(InterruptedException e){e.printstacktrace(); } system.out.println(“ ok2”+system.currentTimeMillis()); } public static void main(string [] args){testlock1(); testlock2(); }第一種是我隨便寫的實現,有點糙。第二種是朋友告知的一個類,java的並發,據說還有幾個相似功能的類實現。這,30000個線程200ms的樣子
以上這篇java父線程(或是主線程)等待所有子線程退出的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。 ,也希望大家多多支持武林網。