使用Automic包中的AtomicBoolean结合CAS来实现。当只希望需要某段代码在多线程中只执行一次的时候,此时你会发现boolean这个变量类型是多么有用。
代码如下
public class AtomicBoolean1{ private static AtomicBoolean isHappened = new AtomicBoolean(false); //初始值设定为fasle,当在多线程环境运行时只希望某段代码只执行一次,则可调用实例isHappened的CAS来仅执行一次。 // private static AtomicInteger isHappened = new AtomicInteger(0); // 请求总数 public static int clientTotal = 5000; // 同时并发执行的线程数 public static int threadTotal = 200; public static void main(String[] args) throws Exception { ExecutorService executorService = Executors.newCachedThreadPool(); final Semaphore semaphore = new Semaphore(threadTotal); final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); for (int i = 0; i < clientTotal ; i++) { executorService.execute(() -> { try { semaphore.acquire(); test(); semaphore.release(); } catch (Exception e) { log.error("exception", e); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); log.info("isHappened:{}", isHappened.get()); } private static void test() { // log.info("execute"); //当前实例的值为false时将其uopdate为true并执行对应代码,否则不执行。 if (isHappened.compareAndSet(false, true)) { log.info("execute"); } } }