一、 整体框架
Excutors是工具类,提供很多便捷的工厂方法。
二、 使用流程
1、创建线程对象
实现Runnable接口重写run方法 或者 Callable 并重写 call方法。
两个实现方法的区别是,后者可以有返回结果。
public class RuntimeCallable implements Callable<Object>{
public String name;
public RuntimeCallable(int i){
this.name = "thread-"+i;
}
public Object call() throws Exception {
Date start = new Date();
Random random = new Random();
Thread.sleep(random.nextInt(1000));
Date end = new Date();
return end.getTime() - start.getTime();
}
}
2、创建线程池
可以创建 ThreadPoolExecutor对象构建线程池,调用execute或者submit方法把 任务加入到线程中去。
int taskSize = 5;
ExecutorService pool = Executors.newFixedThreadPool(5);
List<Future> futureList = new ArrayList();
for(int i=0; i<taskSize; i++){
Callable c = new RuntimeCallable(i);
Future f = pool.submit(c);
futureList.add(f);
}
3、调用Future对象的get方法获取结果,并关闭线程池
pool.shutdown();
for(Future f : futureList){
System.out.println(f.get());
}
参考: