寫一個併發編程的代碼,保證該代碼只能執行一次

錯誤的例子:
@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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章