1. CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
    2. Thread thread1 = new Thread(() -> {
    3. System.out.println(Thread.currentThread().getName()+"[time]"+ new Date()+"[start]");
    4. try {
    5. TimeUnit.SECONDS.sleep(1);
    6. } catch (InterruptedException e) {
    7. throw new RuntimeException(e);
    8. }
    9. try {
    10. cyclicBarrier.await();
    11. } catch (Exception e) {
    12. e.printStackTrace();
    13. }
    14. System.out.println(Thread.currentThread().getName()+"[time]"+ new Date()+"[end]");
    15. },"thread-A");
    16. Thread thread2 = new Thread(() -> {
    17. System.out.println(Thread.currentThread().getName()+"[time]"+ new Date()+"[start]");
    18. try {
    19. TimeUnit.SECONDS.sleep(2);
    20. } catch (InterruptedException e) {
    21. throw new RuntimeException(e);
    22. }
    23. try {
    24. cyclicBarrier.await();
    25. } catch (Exception e) {
    26. e.printStackTrace();
    27. }
    28. System.out.println(Thread.currentThread().getName()+"[time]"+ new Date()+"[end]");
    29. },"thread-B");
    30. thread1.start();
    31. thread2.start();

    cyclicBarrier主要是用于在异步中,多个线程到达某一个时刻后,一起再做下面一件事。
    举例:多个人吃饭,可能出现先到后到,但是都是需要到达 人齐了之后,才会开始吃饭