2010年12月29日 星期三

用 Java 做簡單的 Thread pool

以往用 Java 寫 Thread Pool 並不是簡單的事,不過在 JavaSE 5.0 裡,用幾行 code 就可以:

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class TestExecutor {
public static class Command implements Runnable {
private int id;

public Command(int id) {
this.id = id;
}

public void run() {
System.out.println(id + " Begin " + Thread.currentThread().getName());
try {
Thread.sleep(3000);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println(id + " End " + Thread.currentThread().getName());
}
}

public static void main(String[] args) {
Executor tp = Executors.newFixedThreadPool(3);
tp.execute(new Command(1));
tp.execute(new Command(2));
tp.execute(new Command(3));
tp.execute(new Command(4));
tp.execute(new Command(5));
}
}