Java并发常用的工具以及常见面试题

  • 博客主页:天天困啊
  • 系列专栏:面试题
  • 关注博主,后期持续更新系列文章
  • 如果有错误感谢请大家批评指出,及时修改
  • 感谢大家点赞👍收藏⭐评论✍

常见Java并发工具

CountDownLatch

概念

它是一个允许一个或多个线程等待直到在其他线程中执行的一组操作完成的同步辅助

核心是通过一个计数器实现线程间的协调

核心原理

countDownLatch.countDown()数量-1

countDownLatch.await()等待计数器归零,然后在向下执行

每次有线程调用countDown()数量-1,假设计数器变为0

countDownLatch.await()就会被唤醒,继续执行

样例代码

/**
 * @author 天天困
 * @date 2025/11/14
 */
public class Test01 {
    public static void main(String[] args) throws InterruptedException {
        int num=3;
        CountDownLatch downLatch = new CountDownLatch(num);
        for (int i=0;i<num;i++){
            new Thread(()->{
                System.out.println(Thread.currentThread().getName() + "正在执行");
                try{
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                downLatch.countDown();
                System.out.println(Thread.currentThread().getName() +"已完成");
            }).start();
        }
        downLatch.await();
        System.out.println("所有线程已完成");
    }
}

CyclicBarrier

概念

允许一组线程全部等待彼此达到共同屏障点的同步辅助

屏障被称为循环,因为它可以在等待的线程被释放之后重新使用,与CountDownLatch不同,CyclicBarrier主要注重线程间的相互等待,而不是等待某些操作完成

示例代码

/**
 * @author 天天困
 * @date 2025/11/14
 */
public class Test01 {
    public static void main(String[] args) {
        int num=7;
        CyclicBarrier barrier = new CyclicBarrier(num,()->{
            System.out.println("所有线程已到达屏障,继续执行");
        });
        for (int i=1;i<=num;i++){
            new Thread(()->{
                try {
                    System.out.println(Thread.currentThread().getName() + "正在运行");
                    Thread.sleep(1000);
                    barrier.await();
                } catch (Exception e) {
                   e.printStackTrace();
                }
            }).start();
        }

    }
}

Semaphore

概念

一个计数信号量,信号量维持一组许可证。通过acquire()获取许可,直到许可可用,才能使用。如果没有许可可用,线程将被阻塞,直到有许可被释放。可以通过release方法释放许可

核心原理

emaphore.acquire():获得,假设如果已经满了,等待,等待被释放为止

semaphore.release():释放,会将当前的信号量释放+1,然后唤醒等待的线程

作用:多个共享资源互斥的使用!并发限流,控制最大的线程数

示例代码

/**
 * @author 天天困
 * @date 2025/11/14
 */
public class Test01 {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2);
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "获得了许可");
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "释放了许可");
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
    }
}

Callable

概念

Callable是一个类似于Runnable的接口,但是Runnable不返回结果,也不能抛出异常,它可以有返回值也可以抛出异常,并且和Runnable方法不同的是他是run(),而Callable是call()

示例代码

/**
 * @author 天天困
 * @date 2025/11/14
 */
public class Test01 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Callable<Integer> callable = () ->{
            System.out.println(Thread.currentThread().getName() + "开始执行任务");
            return 1;
        };

        Future<Integer> future = executorService.submit(callable);
        System.out.println("主线程继续执行其他任务");
        try {
            Integer i = future.get();
            System.out.println("任务执行结果为:" + i);
        }catch (Exception e){
            e.printStackTrace();
        }
        executorService.shutdown();
    }
}

Future

概念

Future用于表示一个异步计算的结果,可以通过它来获取Callable任务的执行结果或取消任务

示例代码


/**
 * @author 天天困
 * @date 2025/11/14
 */
public class Test01 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Callable<Integer> callable = () ->{
            System.out.println(Thread.currentThread().getName() + "开始执行任务");
            return 1;
        };

        Future<Integer> future = executorService.submit(callable);
        System.out.println("主线程继续执行其他任务");
        try {
            Integer i = future.get();
            System.out.println("任务执行结果为:" + i);
        }catch (Exception e){
            e.printStackTrace();
        }
        executorService.shutdown();
    }
}

常见面试题

什么是CountDownLatch?

CountDownLatch是Java并发包中的一个同步工具类,他允许一个或多个线程等待其他线程完成操作后再执行,主要是通过一个计数器来实现的,,每当一个线程完成工作后,计数器会递减,当计数器到达零时,所有等待的线程会被唤醒并继续执行

主要功能

  1. 初始化计数器
  2. 通过awit方法等待线程,直到计数器变为0
  3. 其他线程完成任务后通过调用countDown让计数器减1
  4. 当计数器变为0时,所有等待的线程会被唤醒继续执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值