Java多线程求和

Posted 1994july

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
}

} `

 
来源:站长平台

以上是关于Java多线程求和的主要内容,如果未能解决你的问题,请参考以下文章

Java多线程求和

多线程向量求和的可扩展性

java递归阶乘求和,附小技巧

Java多线程——Lock&Condition

Java多线程与并发库高级应用-工具类介绍

Java多线程与并发库高级应用-工具类介绍