JAVA常用并发线程同步器

1、CountDownLatch

  1. 使用场景:主线程需等待子线程执行完成后再进行业务场景。使用Thread.join()方法也能达到此效果,但如果你的线程使用线程池来进行管理,ExecutorService传递的参数是Runable或Callable对象,无法调用join() 方法,需使用CountDownLatch。与CyclicBarrier比较不可循环使用。

  2. 构造函数: new CountDownLatch(int count);

  3. 常用方法:
    await() 阻塞主线程直到容量为0时再往下执行。
    countDown() 容量减1 当容量为零时

  4. 使用实例

public class CountDownLatchDemo {
    // 定义容量为2
    private static final CountDownLatch countDownLatch = new CountDownLatch(2);
    public static void main(String[] args) throws InterruptedException {
        // 定义线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        // 提交线程
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("count down");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 容量-1
                    countDownLatch.countDown();
                }
            }
        });

    /*    executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("count down");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 容量-1
                    countDownLatch.countDown();
                }
            }
        });*/

        System.out.println("wait child thread over");

        // 等待countDownLatch容量为0时执行
        countDownLatch.await();
        System.out.println("child thread over");

    }
}

由于countDownLatch此时的容量为1,主线程阻塞
在这里插入图片描述
将注释代码放开,输出结果如下
在这里插入图片描述

2、CyclicBarrier

  1. 使用场景:多个子线程需达到同一状态再继续往下执行,可循环使用

  2. 构造函数: new CyclicBarrier(int count);

  3. 常用方法:
    当超过N个线程调用await(),所有子线程冲出屏障继续执行剩余任务

  4. 使用实例

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierDemo {

    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new Runnable() {
        @Override
        public void run() {
            // 用于放行时执行的业务操作
            System.out.println("达到循环限制容量,继续向下执行");
        }
    });


    public static void main(String[] args)  {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程1准备工作");

                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }

                System.out.println("线程1完成工作");
            }
        });

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程2准备工作");

                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }

                System.out.println("线程2完成工作");
            }
        });


        executorService.shutdown();
    }
}

3、Semaphore

  1. 使用场景:当线程获取到足够的信号量即可往下执行

  2. 构造函数: new semaphore(int count);

  3. 常用方法:
    release() 释放一个信号量
    release(int count) 释放多个信号量
    acquire() 获取一个信号量
    acquire(int count) 获取多个信号量

  4. 使用实例

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreDemo {

    private static final Semaphore semaphore =new Semaphore(0);;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                // 释放一个信号量
                semaphore.release();
            }
        });

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                // 释放两个信号量
                semaphore.release(2);
            }
        });

        // 需获取三个信号量
        semaphore.acquire(3);

        System.out.println("获取到足够的信号量,继续往下执行");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值