在上篇,我们利用线程池,信号量,倒计时相关类实现计数的功能,但运行结果总不能达到目标,我们将做以下改进。
1.首先附上源码,红色标注,是我们此次修改的地方
import javax.annotation.concurrent.ThreadSafe;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
@ThreadSafe
public class SafeCountExample {
//请求总数
private static int clientTotal = 5000;
//线程数量
private static int threadTotal = 200;
private static AtomicInteger count = new AtomicInteger(0);
public static void main(String[] args) throws Exception{
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
//每次固定数量的线程获取许可
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);