在Java中,Callable接口类似于Runnable,但它可以返回结果并抛出已检查的异常。可以将Callable与ThreadPoolExecutor一起使用来异步执行任务,并获取返回值。
代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class CallableExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
List<Future<Integer>> resultList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Callable<Integer> task = new MyCallable(i);
Future<Integer> future = executor.submit(task);
resultList.add(future);
}
for (Future<Integer> future : resultList) {
try {
System.out.println("Result: " + future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();
}
}
class MyCallable implements Callable<Integer> {
private final int number;
public MyCallable(int number) {
this.number = number;
}
@Override
public Integer call() throws Exception {
System.out.println("Task " + number + " started");
Thread.sleep(1000);
System.out.println("Task " + number + " completed");
return number * number;
}
}
以上代码创建了一个MyCallable类来实现Callable接口,还有一个ThreadPoolExecutitor,其固定池大小为3个线程,向执行器提交10个MyCallable任务,并将Future对象存储在列表中,并可以通过get()方法获取Future对象也就是call函数返回的结果。