package test;
import java.util.concurrent.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;
public class SumService {
private final Integer nthread;
private final ExecutorService executorService;
private final Lock lock;
private final CountDownLatch countDownLatch;
private Integer sum;
public SumService(){
this.sum = new Integer(0);
this.nthread = new Integer(100);
this.executorService = new ThreadPoolExecutor(10, nthread, 10L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(nthread));
this.lock = new ReentrantLock();
this.countDownLatch = new CountDownLatch(nthread);
}
public Integer call() throws Exception{
for (int i = 0; i < nthread; i++) {
executorService.execute(()-> sum());
}
executorService.shutdown();
countDownLatch.await();
return sum;
}
private void sum(){
for (int i = 0; i < 10000; i++) {
lock.lock();
sum++;
lock.unlock();
}
countDownLatch.countDown();
}
public static void main(String[] args) throws Exception{
SumService sumService = new SumService();
Integer sum = sumService.call();
System.out.println(sum);
}
} `