Example using ExecutorService:
public class TaskThreader {
class DoStuff implements Callable {
Object in;
public Object call(){
in = doStep1(in);
in = doStep2(in);
in = doStep3(in);
return in;
}
public DoStuff(Object input){
in = input;
}
}
public abstract Object doStep1(Object input);
public abstract Object doStep2(Object input);
public abstract Object doStep3(Object input);
public static void main(String[] args) throws Exception {
ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
ArrayList<Callable> tasks = new ArrayList<Callable>();
for(Object input : inputs){
tasks.add(new DoStuff(input));
}
List<Future> results = exec.invokeAll(tasks);
exec.shutdown();
for(Future f : results) {
write(f.get());
}
}
}
โค้ดของคุณคนนี้ >> http://stackoverflow.com/users/95122/bobmcgee
- ExecutorService อยู่ใน package ของ java.util.concurrent
-
Runtime.getRuntime().availableProcessors() << อันนี้น่าสนใจ ทำให้เรียกหมายเลขจาก pool (รึป่าว อิอิ)
ดูอีกทีจ้ะ http://stackoverflow.com/questions/1223072/how-do-i-optimize-for-multi-core-and-multi-cpu-computers-in-java