Java:CountDownLatch等待所有线程执行结束后继续执行
【摘要】 CountDownLatch可以使一个或多个线程等待其他线程各自执行完毕后再执行
class WorkThread implements Runnable { private CountDownLatch countDownLatch; public WorkThread(CountDownLatch countDownLatch) { this.countDownL...
CountDownLatch可以使一个或多个线程等待其他线程各自执行完毕后再执行
class WorkThread implements Runnable { private CountDownLatch countDownLatch; public WorkThread(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " 干活结束"); this.countDownLatch.countDown(); }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
package com.demo.atomic;
import java.util.concurrent.CountDownLatch;
public class countDownLatchDemo { public static void main(String[] args) { // 初始化等待线程个数: 2个 CountDownLatch countDownLatch = new CountDownLatch(2); WorkThread workThread1 = new WorkThread(countDownLatch); WorkThread workThread2 = new WorkThread(countDownLatch); new Thread(workThread1).start(); new Thread(workThread2).start(); // 阻塞主线程,等待子线程全部结束继续 try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("结束了"); }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
如果不等待,执行结果
结束了
Thread-0 干活结束
Thread-1 干活结束
- 1
- 2
- 3
如果等待, 执行结果
Thread-1 干活结束
Thread-0 干活结束
结束了
- 1
- 2
- 3
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/112249050
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)