- 原子锁是:Atomic*类的封装类型,如:AtomicInteger、AtomicLong。
- CountDownLatch:是我们熟悉的栅栏,当值为0时就绪否则等待阻塞,最形象的就像赛马,发令枪不响所有马和运动员只能等。
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ClassName: ConcurrencyTest
* @Description: TODO(功能说明:模拟并发请求)
* @author: pengjunlin
* @motto: 学习需要毅力,那就秀毅力
* @date 2020/3/1 22:45
*/
public class ConcurrencyTest {
// 请求总数
public static int clientTotal = 5000;
// 原子锁
public static AtomicInteger count = new AtomicInteger(0);
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal ; i++) {
executorService.execute(() -> {
countDownLatch.countDown();
try {
countDownLatch.await();
add();
} catch (Exception e) {
e.printStackTrace();
}
});
}
try{
//直到方法执行完成
Thread.sleep(10000);
executorService.shutdown();
System.out.println(count);
}catch(InterruptedException e){
e.printStackTrace();
}
}
private static void add() {
count.incrementAndGet();
}
}
boonya 博客专家 发布了628 篇原创文章 · 获赞 535 · 访问量 359万+ 关注