线程不安全:

//请求总次数
private static int totalCount = 10000;
//最大并发数
private static int totalCurrency = 100;
//计数初始值
private static int count = 0;

public static void main(String[] args) throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(totalCount);
final Semaphore semaphore = new Semaphore(totalCurrency);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < totalCount; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
//本身线程不安全
count++;
semaphore.release();
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
//其他线程运行完成执行下面操作
countDownLatch.await();
executorService.shutdown();
System.out.println(count);
}

线程安全:

 //总共请求次数10000次 数值给大点 不然效果不明显
private static int totalCount = 10000;
//最大并发数 100个 数值给大点 不然效果不明显
private static int totalCurrency = 100;
// private static int count = 0;
//使用原子类修饰
private static AtomicInteger atomicInteger = new AtomicInteger(0);

public static void main(String[] args) throws InterruptedException {

final CountDownLatch countDownLatch = new CountDownLatch(totalCount);
final Semaphore semaphore = new Semaphore(totalCurrency);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < totalCount; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
atomicInteger.incrementAndGet();
semaphore.release();
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
//其他线程完成各自任务 countDownLatch.count==0
countDownLatch.await();
executorService.shutdown();
System.out.println(atomicInteger);

}


相关文章:

  • 2022-12-23
  • 2021-06-07
  • 2021-09-23
  • 2021-07-01
  • 2021-09-26
  • 2021-11-25
  • 2022-12-23
  • 2021-06-20
猜你喜欢
  • 2021-06-21
  • 2021-08-29
  • 2021-12-29
  • 2021-05-26
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案