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

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




你可能感兴趣的:(并发编程)