实例如下 :
static void testlock1 () {final atomicinteger waitcount = atomicinteger baru (30000); objek akhir waitoBj = objek baru (); System.out.println ("Start"+System.CurrentTimeMillis ()); untuk (int i = 0; i <30000; i ++) {thread baru (runnable baru () {@Override public void run () {coba {thread.sleep (10);} catch (interruptedException e) {e.printStackTrace ();} waitcount.DecrementException (); {e.printStackTrace ();} waitcount.decrementandget (); {e.printStackRace ();} waitcount.decrementandget (); synchronize (waith) {waitjoned (); waithobon (); {e.printStackTrace ();} waitcount.decrementandget (); }).awal(); } while (waitcount.intvalue ()> 0) {disinkronkan (waitoBj) {if (waitcount.intvalue ()> 0) {coba {waitoBj.wait (); } catch (InterruptedException e) {E.PrintStackTrace (); }}}} System.out.println ("OK"+System.CurrentTimeMillis ()); } static void testLock2 () {final countDownlatch worklauch = countDownlatch baru (30000); // 计数器 System.out.println ("start2"+system.currentTimeMillis ()); untuk (int i = 0; i <30000; i ++) {thread baru (runnable baru () {@Override public void run () {coba {thread.sleep (10);} catch (interruptedException e) {e.printstacktrace ();} worklauch.countdown ();}} () ();} worklauch.countdown ();}; } coba {worklauch.await (); } catch (InterruptedException e) {E.PrintStackTrace (); } System.out.println ("OK2"+System.CurrentTimeMillis ()); } public static void main (string [] args) {testlock1 (); testlock2 (); }第一种是我随便写的实现 , 有点糙。第二种是朋友告知的一个类 , Java 的 Concurrent 中的 , 据说还有几个相似功能的类实现。这 30000 个线程 时间差大概是不到 时间差大概是不到 时间差大概是不到 时间差大概是不到 时间差大概是不到 时间差大概是不到 时间差大概是不到 时间差大概是不到 时间差大概是不到 时间差大概是不到 时间差大概是不到 时间差大概是不到 据说还有几个相似功能的类实现。这 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 200
以上这篇 Java 父线程 (或是主线程) 等待所有子线程退出的实例就是小编分享给大家的全部内容了 , 希望能给大家一个参考 , 也希望大家多多支持武林网。