我有一个线程池为 10 的执行程序服务,我预计会得到 10 条打印输出语句,间隔三秒,但我只收到一条打印输出语句。我传递了 10 作为参数,因此我预计有 10 个线程正在运行。如何检索 10 个 future 对象?
public class Demo {
private static final ExecutorService executor = Executors.newFixedThreadPool(10);
public static void main (String[] args) throws ExecutionException, InterruptedException {
ArrayList futureObjects = new ArrayList();
Callable<Integer> task = () -> {
try {
TimeUnit.SECONDS.sleep(3);
return 123;
}
catch (InterruptedException e) {
throw new IllegalStateException("task interrupted", e);
}
};
System.out.println("Before execution of threads");
Future<Integer> future = executor.submit(task);
Integer result = future.get();
futureObjects.add(future.get());
System.out.println("result: " + result);
for(Object futures : futureObjects ){
System.out.println("Futures in ArrayList: " + futures);
}
}
}
我得到的输出是:
线程执行之前
结果:123
ArrayList 中的 future :123
最佳答案
您实际上只添加了一项任务并提交到线程池,因此执行并返回了一项任务。
您需要一起提交多个任务(使用下面的选项1或选项2),以便您可以实际利用线程池(保持线程繁忙)。
您可以查看以下代码的更新版本:
选项(1):ExecutorService-invokeAll():
private static final ExecutorService executor = Executors.newFixedThreadPool(10);
public static void main (String[] args) throws ExecutionException, InterruptedException {
ArrayList futureObjects = new ArrayList();
Callable<Integer> task = () -> {
try {
TimeUnit.MILLISECONDS.sleep(100);
return 123;
}
catch (InterruptedException e) {
throw new IllegalStateException("task interrupted", e);
}
};
List<Callable<Integer>> callables = new ArrayList<>();
callables.add(task);
callables.add(task);
callables.add(task);
callables.add(task);
//Add other tasks
System.out.println("Before execution of threads");
List<Future<Integer>> futures = executor.invokeAll(callables);
for(Future future : futures ){
System.out.println("Futures in ArrayList: " + future.get());
}
}
选项(2):ExecutorService-submit():
private static final ExecutorService executor = Executors.newFixedThreadPool(10);
public static void main (String[] args) throws ExecutionException, InterruptedException {
ArrayList futureObjects = new ArrayList();
Callable<Integer> task = () -> {
try {
TimeUnit.MILLISECONDS.sleep(100);
return 123;
}
catch (InterruptedException e) {
throw new IllegalStateException("task interrupted", e);
}
};
List<Callable<Integer>> callables = new ArrayList<>();
callables.add(task);
callables.add(task);
callables.add(task);
callables.add(task);
//Add other tasks
List<Future<Integer>> futures = new ArrayList<>();
System.out.println("Before execution of threads");
for(Callable<Integer> callable : callables) {
futures.add(executor.submit(callable));
}
for(Future future : futures ){
System.out.println("Futures in ArrayList: " + future.get());
}
}
可以引用API here
关于java - 执行器不返回 10 个 future 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40433316/