public class callabletry {
class task implements callable<long> {
private long times;
private string name;
public task(long times, string name) {
this.name = name;
this.times = times;
}
@override
public long call() {
system.out.println(name + "開始執行, time[" + times + "]...");
long before = system.currenttimemillis();
for (int i = 0; i < times; i++)
;
long after = system.currenttimemillis();
system.out.println(name + "執行結束.");
long cost = after - before;
system.out.println(name + "耗時 :" + cost);
return cost;
}
}
/**
* @param args
*/
public static void main(string[] args) throws executionexception,
interruptedexception {
long total = 0;
callabletry tr = new callabletry();
executorservice pool = executors.newcachedthreadpool();
random rand = new random();
int count = 10;
for (int i = 0; i < count; i++) {
total += pool.submit(
tr.new task(10000000 * rand.nextint(100), i + "任務")).get();
system.out.println("next task...");
}
pool.shutdown();
while (!pool.isterminated())
;
system.out.println("耗時:" + total + "毫秒, 平均用時:" + total * 1.0 / count
+ "毫秒");
}
}
0任務開始執行, time[860000000]...
0任務執行結束.
0任務耗時 :4750
next task...
1任務開始執行, time[430000000]...
1任務執行結束.
1任務耗時 :2343
next task...
2任務開始執行, time[500000000]...
2任務執行結束.
2任務耗時 :1703
next task...
3任務開始執行, time[990000000]...
3任務執行結束.
3任務耗時 :3344
next task...
4任務開始執行, time[340000000]...
4任務執行結束.
4任務耗時 :1156
next task...
5任務開始執行, time[640000000]...
5任務執行結束.
5任務耗時 :2250
next task...
6任務開始執行, time[880000000]...
6任務執行結束.
6任務耗時 :3032
next task...
7任務開始執行, time[800000000]...
7任務執行結束.
7任務耗時 :2781
next task...
8任務開始執行, time[450000000]...
8任務執行結束.
8任務耗時 :1547
next task...
9任務開始執行, time[980000000]...
9任務執行結束.
9任務耗時 :3375
next task...
耗時:26281毫秒, 平均用時:2628.1毫秒
行了很多次,時間上有差異,但是執行順序卻一直是這個順序...
而把
total += pool.submit( tr.new task(10000000 * rand.nextint(100), i + "任務")).get();改成
next task...
next task...
0任務開始執行, time[880000000]...
next task...
next task...
next task...
next task...
next task...
next task...
next task...
next task...
2任務開始執行, time[790000000]...
1任務開始執行, time[230000000]...
3任務開始執行, time[270000000]...
4任務開始執行, time[490000000]...
5任務開始執行, time[950000000]...
6任務開始執行, time[950000000]...
7任務開始執行, time[630000000]...
8任務開始執行, time[510000000]...
9任務開始執行, time[740000000]...
1任務執行結束.
1任務耗時 :4484
3任務執行結束.
3任務耗時 :5094
7任務執行結束.
7任務耗時 :8281
4任務執行結束.
4任務耗時 :9079
9任務執行結束.
9任務耗時 :9000
8任務執行結束.
8任務耗時 :9860
5任務執行結束.
5任務耗時 :14843
6任務執行結束.
6任務耗時 :15641
2任務執行結束.
2任務耗時 :18297
0任務執行結束.
0任務耗時 :19000