11.线程通信CountDownLatch

 

  1. package demo2;
  2. import java.util.concurrent.CountDownLatch;
  3. /**
  4. * Created by liudan on 2017/7/27.
  5. */
  6. public class DemoCountDownLatch {
  7. public static void main(String[] args) {
  8. final CountDownLatch countDownLatch = new CountDownLatch(3);
  9. Thread t = new Thread(new Runnable() {
  10. @Override
  11. public void run() {
  12. try {
  13. System.err.print(">登录游戏:...\t");
  14. countDownLatch.await();
  15. System.err.println("----------- 登录成功 SUCCESS-------------");
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. },"t");
  21. Thread t1 = new Thread(new Runnable() {
  22. @Override
  23. public void run() {
  24. try {
  25. Thread.sleep(2000);
  26. System.err.print(" 3 ");
  27. countDownLatch.countDown();
  28. } catch (InterruptedException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. },"t1");
  33. Thread t2 = new Thread(new Runnable() {
  34. @Override
  35. public void run() {
  36. try {
  37. Thread.sleep(3000);
  38. System.err.print(" 2 ");
  39. countDownLatch.countDown();
  40. } catch (InterruptedException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. },"t2");
  45. Thread t3 = new Thread(new Runnable() {
  46. @Override
  47. public void run() {
  48. try {
  49. Thread.sleep(4000);
  50. System.err.println(" 1 ");
  51. countDownLatch.countDown();
  52. } catch (InterruptedException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. },"t3");
  57. t.start();
  58. t1.start();
  59. t2.start();
  60. t3.start();
  61. }
  62. }
输出:
>登录游戏:... 3 2 1 ----------- 登录成功 SUCCESS-------------

 




posted @ 2017-08-07 23:12  逍遥叹!!  阅读(117)  评论(0编辑  收藏  举报