CountDownLatch
相当于一个计数器, 使用 countDown() 方法可以对计数器进行减一, 如果计数器的值没有减到 0, 那么 await 方法后面的的都不执行.
- static CountDownLatch c = new CountDownLatch(2);
- public static void main(String[] args) throws InterruptedException {
- new Thread(()->{
- System.out.println(1);
- c.countDown();
- System.out.println(2);
- c.countDown();
- }).start();
- c.await();
- System.out.println(3);
- }
- View Code
同步屏障 CyclicBarrier
让一组线程到达屏障的时候被阻塞, 直到最后一个到达屏障的时候, 所有的线程才会继续执行
- static CyclicBarrier c = new CyclicBarrier(2);
- public static void main(String[] args) {
- new Thread(()->{
- try {
- c.await();
- } catch (InterruptedException | BrokenBarrierException e) {
- e.printStackTrace();
- }
- System.out.println(1);
- }).start();
- try {
- c.await();
- } catch (InterruptedException | BrokenBarrierException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(2);
- }
- View Code
CyclicBarrier 方法功能大致一样, 但是 CyclicBarrier 可以进行 reset 可以多次使用, 适用于复杂的业务场景
Semaphore 信号量
Semaphore 可用作流量控制 两个重要的方法, acquire() 和 release 方法 acquire 方法相当于获取一个许可证, 如果超过了信号量的大小, 则阻塞, release 方法用来归还许可证
- private static final int THREAD_COUNT = 30;
- private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);
- private static Semaphore s = new Semaphore(10);
- public static void main(String[] args) {
- for(int i=0; i<THREAD_COUNT; i++) {
- threadPool.execute(()->{
- try {
- s.acquire();
- System.out.println("save data");
- s.release();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- });
- }
- threadPool.shutdown();
- }
- View Code
- Exchanger
用于线程间的数据交换
在两个同步点 有一个执行 exchange 方法, 会等待第二个线程也执行 exchange 方法, 进行数据交换
- private static final Exchanger<String> change = new Exchanger<String>();
- private static ExecutorService threadPool = Executors.newFixedThreadPool(2);
- public static void main(String[] args) {
- threadPool.execute(()->{
- try {
- String a = "dataA";
- change.exchange(a);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- });
- threadPool.execute(()->{
- try {
- String b = "dataB";
- String exA = change.exchange(b);
- System.out.println(exA);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- });
- threadPool.shutdown();
- }
- View Code
来源: http://www.bubuko.com/infodetail-2771835.html