写一个并发编程的代码,保证该代码只能执行一次

本文探讨如何在多线程环境下编写代码,保证某段关键操作在并发环境中仅执行一次,避免重复和冲突。内容涉及互斥锁、原子操作和单例模式等并发控制策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误的例子:
@ThreadSafe
@Slf4j
public class AtomicExample6 {

    // 总的请求个数
    public static final int requestTotal = 1000;
    // 同一时刻最大的并发线程的个数
    public static final int concurrentThreadNum = 20;

    private static Boolean isHappened_ = false;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(concurrentThreadNum);
        CountDownLatch countDownLatch = new CountDownLatch(requestTotal);
        Semaphore semaphore = new Semaphore(concurrentThreadNum);
        for (int i = 0; i< requestTotal; i++) {
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    test();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("请求完成");
    }
    private static void test() {
        if (isHappened_ == false) {
            isHappened_ = true;
            log.info("hapen 1");
        }
    }
}
分析:
上面的代码先实现只执行一次方法test(),实际上在并发实现的时候可能执行多次。
输出结果:
[pool-1-thread-3] INFO com.example.concurrent.example.count.AtomicExample6 - hapen 1
[pool-1-thread-2] INFO com.example.concurrent.example.count.AtomicExample6 - hapen 1
[main] INFO com.example.concurrent.example.count.AtomicExample6 - 请求完成
正确的程序代码(通过AtomicBoolean):
@ThreadSafe
@Slf4j
public class AtomicExample6 {

    // 总的请求个数
    public static final int requestTotal = 1000;
    // 同一时刻最大的并发线程的个数
    public static final int concurrentThreadNum = 20;
    private static AtomicBoolean isHappened = new AtomicBoolean(false);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(concurrentThreadNum);
        CountDownLatch countDownLatch = new CountDownLatch(requestTotal);
        Semaphore semaphore = new Semaphore(concurrentThreadNum);
        for (int i = 0; i< requestTotal; i++) {
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    test();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("请求完成");
    }

    private static void test() {
        if (isHappened.compareAndSet(false, true)) {  // 这段代码可以保证执行执行一次
            log.info("happen 1");
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值