ExecutorService executorService = Executors.newCachedThreadPool();
//10个FutureTask
List<FutureTask> futureTasks = new ArrayList<>();
for (int i = 0; i < 10; i++) {
futureTasks.add(new FutureTask<>(new Callable<String>() {//FutrueTask的构造参数是一个Callable接口或runnable接口
@Override
public String call() throws Exception {
Thread.currentThread().sleep(1000);
return Thread.currentThread().getName();//这里是异步操作
}
}));
}
executorService.invokeAll(futureTasks);
最后一行提示:没有这个构造器。为什么?
------解决方案--------------------
FutureTask没有实现Callable
------解决方案--------------------
ExecutorService executorService=Executors.newCachedThreadPool();
//10个FutureTask
List<FutureTask> futureTasks=new ArrayList<>();
for (int i=0; i<10; i++) {
futureTasks.add(new FutureTask<>(new Callable<String>() {//FutrueTask的构造参数是一个Callable接口或runnable接口
@Override
public String call() throws Exception {
Thread.currentThread();
Thread.sleep(1000);
return Thread.currentThread().getName();//这里是异步操作
}
}));
}
for (FutureTask futureTask : futureTasks) {
executorService.execute(futureTask);
}
------解决方案--------------------
for (FutureTask futureTask : futureTasks) {
executorService.execute(futureTask);
}
------解决方案--------------------
2楼正解!