Guest User

Untitled

a guest
May 23rd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. package com.spell.threads;
  2.  
  3. import java.util.concurrent.CountDownLatch;
  4.  
  5. public class CountDownLatchTest {
  6.  
  7. /**
  8. * @param args
  9. */
  10. public static void main(String[] args) {
  11. // 构造参数为1,可以作为开始开关,只有等他countDown后才开始处理所有的线程
  12. CountDownLatch start = new CountDownLatch(1);
  13. CountDownLatch done = new CountDownLatch(5);
  14. Worker wk = new Worker(start, done);
  15. for (int i = 0; i < 5; i++) {
  16. new Thread(wk).start();
  17. }
  18. System.out
  19. .println(System.currentTimeMillis() + " all thread has start");
  20. // 发送开始信号,通知所有线程该工作了
  21. start.countDown();
  22. try {
  23. // 等待所有的线程工作完成
  24. done.await();
  25. System.out.println(System.currentTimeMillis()
  26. + " all thread has done");
  27. } catch (InterruptedException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31.  
  32. }
  33.  
  34. class Worker implements Runnable {
  35. private final CountDownLatch start;
  36. private final CountDownLatch done;
  37.  
  38. Worker(CountDownLatch start, CountDownLatch done) {
  39. this.start = start;
  40. this.done = done;
  41. }
  42.  
  43. public void run() {
  44. try {
  45. // 阻塞,等待开始信号
  46. start.await();
  47. doWork();
  48. // 发送线程完成信号
  49. done.countDown();
  50. } catch (InterruptedException e) {
  51. e.printStackTrace();
  52. }
  53.  
  54. }
  55.  
  56. // 工作的任务就睡打个盹
  57. public void doWork() {
  58. // 产生个随机数
  59. Double d = Math.random() * 1000L;
  60. Long sleepTime = d.longValue();
  61. try {
  62. // 睡觉
  63. Thread.sleep(sleepTime);
  64. } catch (InterruptedException e) {
  65. e.printStackTrace();
  66. }
  67. // 睡晚了报告时间
  68. System.out.println(Thread.currentThread().getName() + " sleep "
  69. + sleepTime + " seconds");
  70. }
  71. }
Add Comment
Please, Sign In to add comment