緩存線程池-newCachedThreadPool (搬遷至此)

緩存線程池與固定線程池的區別在於對於需要執行很多短期異步任務的程序來說,緩存線程池可以提高程序性能,因爲長時間保持空閒的這種類型的線程池不會佔用任何資源,調用緩存線程池對象將重用以前構造的線程(線程可用狀態),若線程沒有可用的,則創建一個新線程添加到池中,緩存線程池將終止並從池中移除60秒未被使用的線程。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestCahedThread {
public static void main(String[] args){
ExecutorService exec=Executors.newCachedThreadPool();
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();
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章