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

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

错误的例子:
@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.rele
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值