实现Callable接口,重写call()方法,使操作线程池时能带有返回值的效果:
import java.util.concurrent.Callable;
public class GetSumCallable implements Callable<Integer> {
private int a;
public GetSumCallable(int a) {
this.a = a;
}
public Integer call() {
int sum = 0;
for (int i = 1; i <= a; i++)
sum += i;
return sum;
}
}
将线程放入线程池中,实现异步运算:
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class GetSumThreadPoolDemo {
public static void main(String[] args) throws Exception, ExecutionException {
// 创建一个线程数为2的线程池
ExecutorService es = Executors.newFixedThreadPool(2);
// 将线程放入线程池中运行,将返回值封装成Future接口实现类对象
Future<Integer> f1 = es.submit(new GetSumCallable(100));
Future<Integer> f2 = es.submit(new GetSumCallable(200));
// 调用Future接口实现类对象,获得封装的值并输出
System.out.println(f1.get());
System.out.println(f2.get());
// 销毁线程池
es.shutdown();
}
}