Java Executors
今天要做的東西需要用到多線程執行一系列的Task,查了一下網絡,決定用java的Executors來做。下面是寫的一段測試代碼。
TestTask.java

public class Main {
public static void main(String[] args) {
TestThread[] tt=new TestTask[10];
ExecutorService pool=Executors.newFixedThreadPool(5);
for(int i=0;i<10;i++ ){
tt[i]=new TestTask(i);
pool.execute(tt[i]);
}
pool.shutdown();
try {
pool.awaitTermination(100, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Finished");
}


public class Main {
public static void main(String[] args) {
TestThread[] tt=new TestTask[10];
ExecutorService pool=Executors.newFixedThreadPool(5);
for(int i=0;i<10;i++ ){
tt[i]=new TestTask(i);
pool.execute(tt[i]);
}
pool.shutdown();
try {
pool.awaitTermination(100, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Finished");
}
很簡單的一段代碼,注意在Main.java中,shutdown()是必須要調用的,不然ExecutorService不會關閉,程序不會退出。
整個程序的執行結果正如你所想看到的,會先執行完前五個task,然后再執行后五個,最后打印"Finished"并退出。