问题描述
我有嵌套循环.我知道没有办法减少嵌套循环完成所需的时间.但是我们如何使用多线程或执行器服务更快地完成循环.
I have nested loops. I understand there is no way of decreasing the time taken by the nested loops to complete. But how can we complete the loop faster using multithreading or executor Service.
例如:
for(String str : ListA){
for(String str1 : ListB){
for(String str2 : ListC){
//do Something
}
}
}
所以我知道完成循环需要 MNP(其中 M,N,P 是列表的大小)时间.但是我如何在这里利用多线程并通过执行异步作业更快地完成循环.我想使用 Executor Service,因为我使用的是 java 7(不能使用并行流).
So i understand it takes MNP(where M,N,P are the size of the List) times to complete the loop. But how can i make use of multithreading here and complete the loop faster by performing asynchronous jobs. I want to use Executor Service as i am using java 7 (Parallel Streams cannot be used).
我试过了:
ExecutorService executor = Executors.newFixedThreadPool(10);
for(String str : ListA){
executor.execute(new Runnable() {
@Override
public void run() {
for(String str1 : ListB){
for(String str2 : ListC){
//do Something
}
}
} });
}
但我相信上面的过程是启动线程 10 次,但执行相同的事情 10 次,这不是循环的工作原理.请问有人可以建议我如何使用 Java 中的多线程执行程序服务来完成这个循环吗?
But i believe in the above process is starting the thread 10 times but executing the same thing 10 times and thats not how looping works. Can anyb one please suggest me how to complete this looping using multithreading executor Service in Java please?
推荐答案
Loop 足够快,您无需对其进行优化.如果有阻塞行为,你在//do something 中执行的实际代码可能是一个问题.在这种情况下,您可以执行以下操作
Loop is fast enough you don't have to optimize it. The actual code what you are performing in //do something can be a problem it if has blocking behaviour. In that case you can do the following
ExecutorService executor = Executors.newFixedThreadPool(10);
List<String> level1 = Arrays.asList("1", "2", "3");
List<String> level2 = Arrays.asList("a", "b", "c");
List<String> level3 = Arrays.asList("x", "y", "z");
for(String l1 : level1){
for(String l2 : level2){
for(String l3 : level3){
executor.execute(new Runnable() {
@Override
public void run() {
get("http://foo.com/"+l1+"/"+l2+"/"+l3);
}
});
}
}
}
这篇关于使用多线程异步循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!