Alv*_*das 1 java concurrency multithreading
我刚开始使用java中的线程.我有一个简单的算法,可以进行大量的计算.我需要做的是在不同的线程之间划分这些计算.它看起来像这样:
while(...) {
....
doCalculations(rangeStart, rangeEnd);
}
Run Code Online (Sandbox Code Playgroud)
而我想要做的是这样的事情:
while(...) {
...
// Notify N threads to start calculations in specific range
// Wait for them to finish calculating
// Check results
... Repeat
}
Run Code Online (Sandbox Code Playgroud)
计算线程不必具有关键部分或彼此之间同步,因为它们不会更改任何共享变量.
我无法弄清楚的是如何命令线程开始并等待它们完成.
thread [n] .start()和thread [n] .join()抛出异常.
谢谢!
我使用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.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1091 次 |
| 最近记录: |