廢話不多說直接上代碼
/**
* 固定大小的線程池
*
* 同時可以處理【參數】個任務,多餘的任務會排隊,當處理完一個馬上就會去接着處理排隊中的任務。
* 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");
}
轉載望轉客附上本主連接,謝謝