在多个线程之间划分计算

时间:2012-12-15 15:14:16

标签: java multithreading concurrency

我刚开始使用java中的线程。我有一个简单的算法,可以进行大量的计算。我需要做的是在不同的线程之间划分这些计算。它看起来像这样:

while(...) {
      ....
      doCalculations(rangeStart, rangeEnd);
}

我想要做的是这样的事情:

while(...) {
     ...
     // Notify N threads to start calculations in specific range

     // Wait for them to finish calculating

     // Check results

     ... Repeat

}

计算线程不必具有关键部分或彼此之间同步,因为它们不会更改任何共享变量。

我无法弄清楚如何命令线程开始并等待它们完成。

thread [n] .start()和thread [n] .join()抛出异常。

谢谢!

3 个答案:

答案 0 :(得分:5)

我使用ExecutorService

private static final int procs = Runtime.getRuntime().availableProcessors();
private final ExecutorService es = new Executors.newFixedThreadPool(procs);

int tasks = ....
int blockSize = (tasks + procss -1) / procs;
List<Future<Results>> futures = new ArrayList<>();

for(int i = 0; i < procs; i++) {
    int start = i * blockSize;
    int end = Math.min(tasks, (i + 1) * blockSize);
    futures.add(es.submit(new Task(start, end));
}

for(Future<Result> future: futures) {
    Result result = future.get();
    // check/accumulate result.
}

答案 1 :(得分:4)

使用CountDownLatch启动,另一个CountDownLatch完成:

CountDownLatch start = new CountDownLatch(1);
CountDownLatch finish = new CountDownLatch(NUMBER_OF_THREADS);
start.countDown();
finish.await();

在每个工作线程中:

start.await();
// do the computation
finish.countDown();

如果你需要多次这样做,那么你应该使用CyclicBarrier

答案 2 :(得分:0)

了解MapReduceHadoop。我认为这可能是一种比滚动自己更好的方法,但代价是更大的依赖性。