Friday, November 3, 2006

Use Executors to create thread pool in JavaSE 5

JavaSE 5 introduces the Executors makes creating Thread Pool much simplier:
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));  
    }  
}  
And below is the result:   
1 Begin pool-1-thread-1
2 Begin pool-1-thread-2
3 Begin pool-1-thread-3
1 End   pool-1-thread-1
4 Begin pool-1-thread-1
2 End   pool-1-thread-2
5 Begin pool-1-thread-2
3 End   pool-1-thread-3
4 End   pool-1-thread-1
5 End   pool-1-thread-2