CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
Thread thread1 = new Thread(() -> {
System.out.println(Thread.currentThread().getName()+"[time]"+ new Date()+"[start]");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"[time]"+ new Date()+"[end]");
},"thread-A");
Thread thread2 = new Thread(() -> {
System.out.println(Thread.currentThread().getName()+"[time]"+ new Date()+"[start]");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"[time]"+ new Date()+"[end]");
},"thread-B");
thread1.start();
thread2.start();
cyclicBarrier主要是用于在异步中,多个线程到达某一个时刻后,一起再做下面一件事。
举例:多个人吃饭,可能出现先到后到,但是都是需要到达 人齐了之后,才会开始吃饭