使用join和CountDownLatch来等待线程结束
Posted zhshlimi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用join和CountDownLatch来等待线程结束相关的知识,希望对你有一定的参考价值。
1.join方法的实现
join只能在start()之后调用,
调用线程会等待子线程结束后再运行
public class ThreadJoinTest { public static void main(String[] args) { int count = 100; Thread[] threads = new Thread[count]; IntStream.range(0, count) .forEach(i -> { threads[i] = new Thread("thread" + i) { @Override public void run() { ThreadJoinTest.sleep(1); System.out.println(Thread.currentThread().getName() + ":" + i); } }; threads[i].start(); }); //join只能在start()之后调用 //调用线程会等待子线程结束后再运行 Arrays.stream(threads).forEach(ThreadJoinTest::join); System.out.println("over"); }
private static void sleep(int seconds) { try { TimeUnit.SECONDS.sleep(seconds); } catch (InterruptedException ex) { } } private static void join(Thread thread) { try { thread.join(); } catch (InterruptedException ex) { } }
测试结果如下
thread2:2 thread10:10 thread6:6 thread14:14 thread18:18 thread34:34 thread22:22 thread26:26 thread30:30 thread38:38 thread42:42 thread46:46 thread50:50 thread54:54 thread62:62 thread66:66 thread58:58 thread70:70 thread74:74 thread78:78 thread82:82 thread86:86 thread90:90 thread94:94 thread98:98 thread5:5 thread1:1 thread9:9 thread13:13 thread17:17 thread21:21 thread25:25 thread29:29 thread33:33 thread37:37 thread41:41 thread45:45 thread49:49 thread61:61 thread57:57 thread53:53 thread77:77 thread73:73 thread69:69 thread65:65 thread93:93 thread89:89 thread85:85 thread81:81 thread97:97 thread0:0 thread12:12 thread4:4 thread8:8 thread16:16 thread20:20 thread24:24 thread28:28 thread32:32 thread36:36 thread40:40 thread44:44 thread60:60 thread56:56 thread52:52 thread48:48 thread76:76 thread72:72 thread68:68 thread64:64 thread92:92 thread88:88 thread84:84 thread80:80 thread96:96 thread3:3 thread7:7 thread11:11 thread99:99 thread95:95 thread91:91 thread87:87 thread83:83 thread79:79 thread75:75 thread67:67 thread63:63 thread71:71 thread59:59 thread51:51 thread55:55 thread23:23 thread27:27 thread31:31 thread35:35 thread39:39 thread43:43 thread47:47 thread15:15 thread19:19 over
2. java.util.concurrent.CountDownLatch
public class ThreadJoinTest { public static void main(String[] args) { int count = 100; Thread[] threads = new Thread[count]; java.util.concurrent.CountDownLatch countDownLatch = new java.util.concurrent.CountDownLatch(count); IntStream.range(0, count) .forEach(i -> { threads[i] = new Thread("thread" + i) { @Override public void run() { ThreadJoinTest.sleep(1); System.out.println(Thread.currentThread().getName() + ":" + i);
//只能在run方法的最后一句,或者在 try..finally的 finally里 countDownLatch.countDown(); } }; threads[i].start(); }); try { countDownLatch.await(); } catch (InterruptedException ex) { } System.out.println("over"); }
以上是关于使用join和CountDownLatch来等待线程结束的主要内容,如果未能解决你的问题,请参考以下文章
Join,CountDownLatch,CyclicBarrier,Semaphore和Exchanger
并发编程常用工具类之countDownLatch和cyclicBarrier的使用对比
java 并发多线程 : 主线程等待子线程结束的三种方式:join / CountDownLatch / CyclicBarrier