Java多线程求和

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); } 

} `

 
来源: 站长平台

猜你喜欢

转载自www.cnblogs.com/1994july/p/12163944.html