固定線程池就不用說了,看看就知道了,主要是編寫人員不用關注線程池如何排程線程,隻用關注線程任務上,使用起來非常友善。
import java.util.concurrent.*;
public class TestThreadPool {
public static void main(String[] args){
//建立容量為5的線程池
ExecutorService exec=Executors.newFixedThreadPool(5);
for(int index=0;index<10;index++){
Runnable run=new Runnable(){
public void run(){
long time=(long)(Math.random()*1000);
System.out.println("sleep:"+time+" ss ");
try{
Thread.sleep(time);
}catch (Exception e) {
// TODO: handle exception
}
}
};
exec.execute(run);
}
exec.shutdown();
}
}