public class ThreadPoolsTest {
public static void main(String[] args) {
//ExecutorService threadpools = Executors.newFixedThreadPool(3);//固定線程池
//ExecutorService threadpools = Executors.newCachedThreadPool();//緩衝線程池,來多少就開多少線程
ExecutorService threadpools = Executors.newSingleThreadExecutor();//單個線程池,死掉了就重啟一個線程
for(int i=0;i<10;i++){
final int task = i;
threadpools.execute(new Runnable(){
public void run(){
for(int j=0;j<10;j++){
System.out.println(Thread.currentThread().getName()+"is from pools" +task);
}
}
});
}
threadpools.shutdown();//停掉線程池
//定時器,隔10s後執行
Executors.newScheduledThreadPool(3).schedule(new Runnable(){
public void run(){
System.out.println("-----");
}
}, 10, TimeUnit.SECONDS);
//定時器,隔10s後執行,並每2s執行一次
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable(){
public void run(){
System.out.println("-----");
}
}, 10,2, TimeUnit.SECONDS);
}
}