Java多线程求和

自作多情 提交于 2020-01-07 19:32:13

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

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

} `

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!