我对照视频的代码写了,为啥会出现线程不安全的情况?

来源: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回答

Jimin

2018-07-09

你好,final CountDownLatch countDownLatch = new CountDownLatch(threadTotal); 这个参数传错了,应该是为5000那个变量,否则await方法提前释放锁了,导致过早的打印count值了,你改一下试试看

0
1
HHbios
非常感谢!
2018-07-09
共1条回复

Java高并发编程,构建并发知识体系,提升面试成功率

构建完整并发与高并发知识体系,倍增高薪面试成功率!

3923 学习 · 832 问题

查看课程