废话不多说直接上代码
/**
* 固定大小的线程池
*
* 同时可以处理【参数】个任务,多余的任务会排队,当处理完一个马上就会去接着处理排队中的任务。
* Callable的任务在后面的blog有更详细的文章说明
*/
private static void fixedThreadPool(){
long startTime = System.currentTimeMillis();
// TODO 创建20个线程
ExecutorService es = Executors.newFixedThreadPool(20);
// TODO callable way
for(int i=1; i <= 1000; i++){
final int task = i;
Future<Integer> future = es.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int status = 0;
try {
Thread.sleep(100);
Car car = new Car();
car.setGeoCode("12");
// TODO 加入自己写的接口
// status= carService.save(car);
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
});
}
// TODO 结束所有线程
es.shutdown();
// TODO 这个方法是统计所有线程全部执行完毕的时间
while(true){
if(es.isTerminated()){
long end = System.currentTimeMillis();
System.out.println("20个线程执行用时: " + (end - startTime) + "ms");
break;
}
}
// TODO 以下是单线成保存1000条记录的时间
long startTime1 = System.currentTimeMillis();
for (int f = 0; f < 1000; f++) {
Car car = new Car();
car.setGeoCode("12");
// TODO 换成自己的实现类即可
// carService.save(car);
}
long endTime1 = System.currentTimeMillis();
System.out.println("执行时间单线程" + (endTime1 - startTime1) + "ms");
// TODO runnable 没有线程返回值不做具体详解
// for(int i=1 ; i<5000; i++){
// final int task = i;
// es.execute(new Runnable() {
// @Override
// public void run() {
// for(int j=1; j<=2000; j++){
// System.out.println(Thread.currentThread().getName());
// try {
// Thread.sleep(100);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
// });
// }
// long endTime = System.currentTimeMillis();
// System.out.println((endTime - startTime) + "ms");
}
转载望转客附上本主连接,谢谢