码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程求和

时间:2020-01-07 22:55:15      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:class   adp   executor   i++   pre   unit   queue   run   cal   

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

} `

 
来源:站长平台

Java多线程求和

标签:class   adp   executor   i++   pre   unit   queue   run   cal   

原文地址:https://www.cnblogs.com/1994july/p/12163944.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!