我对照视频的代码写了,为啥会出现线程不安全的情况?
来源:3-1 线程安全性-原子性-atomic-1
HHbios
2018-07-09
@Slf4j
public class ConcurrencyTest {
//请求总数
public static int clientotal = 5000;
//同事并发执行的线程数
public static int threadTotal = 200;
public static AtomicInteger count= new AtomicInteger(0) ;
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(clientotal);
final CountDownLatch countDownLatch = new CountDownLatch(threadTotal);
for (int i = 0; i < clientotal; i++){
executorService.execute(()->{
try {
semaphore.acquire();
add();
semaphore.release();
} catch (InterruptedException e) {
log.error("exception",e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
log.info("count:{}",count.get());
}
private static void add(){
count.incrementAndGet();
}
}
16:32:44.985 [main] INFO com.mmall.concurrency.ConcurrencyTest - count:4881
1回答
-
你好,final CountDownLatch countDownLatch = new CountDownLatch(threadTotal); 这个参数传错了,应该是为5000那个变量,否则await方法提前释放锁了,导致过早的打印count值了,你改一下试试看
012018-07-09
相似问题
回答 2
回答 1