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

错误的例子:
@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");
        }
    }
}




发布了164 篇原创文章 · 获赞 114 · 访问量 69万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章