实例如下
estático void testlock1 () {final atomicinteger waitcount = new atomicinteger (30000); objeto final wagoobj = new Object (); System.out.println ("start"+system.currenttimemillis ()); para (int i = 0; i <30000; i ++) {new Thread (new Runnable () {@Override public void run () {try {thread.sleep (10);} catch (interruptEdException e) {e.printStacktrace ();} waitcount.decRementEndGet (); }).começar(); } while (WaitCount.IntValue ()> 0) {Synchronized (WaitObj) {if (WaitCount.IntValue ()> 0) {try {waitobj.wait (); } catch (interruptedException e) {e.printStackTrace (); }}}} System.out.println ("ok"+System.currenttimemillis ()); } estático void testlock2 () {Final CountDownLatch Worklauch = new Countdownlatch (30000); // 计数器 System.out.println ("start2"+System.currenttimemillis ()); para (int i = 0; i <30000; i ++) {new Thread (new Runnable () {@Override public void run () {try {thread.sleep (10);} catch (interrupedException e) {e.printstacktrace ();} worklach.countdown ();}). } tente {worklauch.await (); } catch (interruptedException e) {e.printStackTrace (); } System.out.println ("ok2"+System.currenttimemillis ()); } public static void main (string [] args) {testlock1 (); testlock2 (); }第一种是我随便写的实现 , 有点糙。第二种是朋友告知的一个类 , Java 的 Concorrente 中的 , 据说还有几个相似功能的类实现。这 30000 个线程 时间差大概是不到 200ms 的样子
以上这篇 Java 父线程 (或是主线程) 等待所有子线程退出的实例就是小编分享给大家的全部内容了 , 希望能给大家一个参考 , 也希望大家多多支持武林网。