测试老兵 算法学习第二题--两个线程分别打印 0-100 之间的奇偶数

CC · January 04, 2019 · 975 hits

采用 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();

    }

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
No Reply at the moment.
需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up