public class ThreadTest {
private static int threadTotal = 200;
private static int clientTotal = 5000;
private static int count = 0;
public static void main(String[] args) throws InterruptedException {
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();
++count;
semaphore.release();
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
countDownLatch.await();
System.out.println(count);
executorService.shutdown();
}
}这段代码操作的是一个static 变量,5000个线程执行了5000次++操作,为什么结果是线程不安全的
一凡
相关分类