Bob*_*Bob 1 java multithreading for-loop
假设我有一个非常缓慢且大的for循环.
如何在多个线程中拆分它以便它运行得更快?
for (int a = 0; a < 30000000; a++) {
for (int b = 0; b < 30000000; b++) {
for (int c = 0; c < 30000000; c++) {
slowMethod();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这有点宽泛,但是ExecutorService当处理器数量大于1并且它slowMethod是独立的时,使用具有固定线程数的将使其更快.如果slowMethod是I/O密集型,您可以增加线程数以获得更高的性能.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors() + 1);
for (int a = 0; a < 30000000; a++) {
for (int b = 0; b < 30000000; b++) {
for (int c = 0; c < 30000000; c++) {
final int a_copy = a;
final int b_copy = b;
final int c_copy = c;
service.execute(() -> {
slowMethod(a_copy, b_copy, c_copy);
});
}
}
}
}
public static void slowMethod(int a, int b, int c) {
}
}
Run Code Online (Sandbox Code Playgroud)
更新
正如评论中所说,它可能导致任务中止,因为队列的容量是Integer.MAX_VALUE.您可以slowMethod在队列已满时让主线程执行.要实现此目的,您需要手动创建池:
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
int threads = Runtime.getRuntime().availableProcessors();
ThreadPoolExecutor executor = new ThreadPoolExecutor(threads, threads,
0, TimeUnit.MILLISECONDS,
queue, Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
146 次 |
| 最近记录: |