package com.springboot.thread;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/*
* 以CycliclBarrier的方式进行线程之间的通信:
* (1).CycliclBarrier是在java1.5以后被引入的,存在于java.concurrent包下
* (2).CycliclBarrier实现让一组线程等待至某个状态以后再全部同时执行
* (3).CycliclBarrier底层基于ReentrantLock和condition实现
* 本文示例:保证三个线程在同一时刻启动
* */
public class ThreadCommunication4 {
/*参数是参与CyclicBarrier的线程数*/
private CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
public void startThread(){
String name = Thread.currentThread().getName();
System.out.println(name+"正在准备...");
/*调用CyclicBarrier等待线程全部准备完毕*/
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
/*线程准备完毕*/
System.out.println(name+"线程启动完毕!"+new Date());
}
public static void main(String[] args) {
final ThreadCommunication4 threadCommunication4 = new ThreadCommunication4();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
threadCommunication4.startThread();
}
},"thread1");
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
threadCommunication4.startThread();
}
},"thread2");
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
threadCommunication4.startThread();
}
},"thread3");
thread1.start();
thread2.start();
thread3.start();
}
}
运行结果:
thread1正在准备...
thread2正在准备...
thread3正在准备...
thread3线程启动完毕!Mon Sep 23 14:58:55 CST 2019
thread1线程启动完毕!Mon Sep 23 14:58:55 CST 2019
thread2线程启动完毕!Mon Sep 23 14:58:55 CST 2019