实例如下 :
static void twitlock1 () {final AtomicInteger WaitCount = new AtomicInteger (30000); objeto final waitobj = nuevo objeto (); 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);} capt (interruptedException e) {e.PrintStackTrace ();} }).comenzar(); } while (waitCount.intvalue ()> 0) {sincronizado (waitobj) {if (waitCount.intvalue ()> 0) {try {waitobj.wait (); } catch (InterruptedException e) {E.PrintStackTrace (); }}}} System.out.println ("OK"+System.CurrentTimemillis ()); } static void twitlock2 () {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 ();} Worklauch.Countdown ();}). Start (); } try {worklauch.await (); } catch (InterruptedException e) {E.PrintStackTrace (); } System.out.println ("OK2"+System.CurrentTimemillis ()); } public static void main (string [] args) {twitlock1 (); TIPTLOCK2 (); }第一种是我随便写的实现 , 有点糙。第二种是朋友告知的一个类 , java 的 concurrente 中的 , 据说还有几个相似功能的类实现。这 30000 个线程 时间差大概是不到 200 ms 的样子
以上这篇 java 父线程 (或是主线程) 等待所有子线程退出的实例就是小编分享给大家的全部内容了 , 希望能给大家一个参考 也希望大家多多支持武林网。