我在java中使用了ExecutorService和FutureTask在for循环中执行并行操作。以下是代码
package com.sample.threading.parallel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class Combinations {
public static String[] fillArray(int range) {
String a[] = new String[100];
for (int i = ((10 * range) + 1); i < (10 * (range + 1)); i++) {
a[i] = "Name " + i;
}
return a;
}
public static String[] futureFillArray() throws Exception {
String a[] = new String[100];
int threadNum = 2;
ExecutorService executor = Executors.newFixedThreadPool(threadNum);
List<FutureTask<String[]>> taskList = new ArrayList<FutureTask<String[]>>();
FutureTask<String[]> futureTask = new FutureTask<String[]>(
new Callable<String[]>() {
@Override
public String[] call() throws Exception {
return fillArray(0);
}
});
taskList.add(futureTask);
executor.execute(futureTask);
FutureTask<String[]> futureTask1 = new FutureTask<String[]>(
new Callable<String[]>() {
@Override
public String[] call() throws Exception {
return fillArray(1);
}
});
taskList.add(futureTask1);
executor.execute(futureTask1);
FutureTask<String[]> futureTask2 = new FutureTask<String[]>(
new Callable<String[]>() {
@Override
public String[] call() throws Exception {
return fillArray(2);
}
});
taskList.add(futureTask2);
executor.execute(futureTask2);
FutureTask<String[]> futureTask3 = new FutureTask<String[]>(
new Callable<String[]>() {
@Override
public String[] call() throws Exception {
return fillArray(3);
}
});
taskList.add(futureTask3);
executor.execute(futureTask3);
for (int j = 0; j < threadNum; j++) {
FutureTask<String[]> futureTaskF = taskList.get(j);
a = futureTaskF.get();
}
executor.shutdown();
return a;
}
}
我知道我必须调用 fillArray 方法10 次,但我只调用了 3 次。以下是执行类
package com.sample.threading.parallel;
import java.util.Calendar;
public class ExecuteCombinations {
public static void main(String[] args) throws Exception {
long timeStart = Calendar.getInstance().getTimeInMillis();
String res[] = Combinations.fillArray(0);
long timeEnd = Calendar.getInstance().getTimeInMillis();
long timeNeeded = timeEnd - timeStart;
System.out.println("Result : " + res + " calculated in " + timeNeeded + " ms");
// Parallel execution
long timeStartFuture = Calendar.getInstance().getTimeInMillis();
String res2[] = Combinations.futureFillArray();
long timeEndFuture = Calendar.getInstance().getTimeInMillis();
long timeNeededFuture = timeEndFuture - timeStartFuture;
System.out.println("Result (Future): " + res2 + " calculated in " + timeNeededFuture + " ms");
}
}
但仍然是输出
Result : [Ljava.lang.String;@773d3f62 calculated in 0 ms
Result (Future): [Ljava.lang.String;@47b6617 calculated in 16 ms
我的实现有误吗?请告知
我不确定我是否正确理解了你。你想知道为什么尽管运行 3 个期货,你只得到两行输出,对吧?如果是这种情况,您只需调整String res2[] = Combinations.futureFillArray();
的打印(即使用 for
循环迭代res2[]
中的所有条目即可查看所有结果。