采用 AtomicInteger 的 CAS 锁方式进行多线程处理 (非分布式做法)

private static AtomicInteger TOTAL_COUNT = new AtomicInteger(0);

    @Test
    public void testThread(){
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while(TOTAL_COUNT.intValue() < 100) {
                    if (TOTAL_COUNT.intValue() % 2 == 0) {
                        System.out.println("ThreadA:" + TOTAL_COUNT.incrementAndGet());
                    }
                }
            }
        });

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while(TOTAL_COUNT.intValue() < 100) {
                    if (TOTAL_COUNT.intValue() % 2 == 1) {
                        System.out.println("ThreadB:" + TOTAL_COUNT.incrementAndGet());
                    }
                }
            }
        });

        executorService.shutdown();

    }


↙↙↙阅读原文可查看相关链接,并与作者交流