采用 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();
}
转载文章时务必注明原作者及原始链接,并注明「发表于 TesterHome 」,并不得对作品进行修改。
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。