線程池

java.util.concurrent.Executors 可以創建三種類型的線程池
建立一個線程池,把要執行的任務丟到線程池中。
package traditional;
 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
 
public class ThreadPoolTest {
 
   public static void main(String[] args) {
      //創建線程池
//    ExecutorService threadPool = Executors.newFixedThreadPool(3);//固定線程池
//    ExecutorService threadPool = Executors.newCachedThreadPool();//動態變化線程數的線程池
      ExecutorService threadPool = Executors.newSingleThreadExecutor();//創建的線程池中只有一個線程,(一個線程死掉後就會立即創建一個線程,確保線程池中有一個線程)
      //給線程池添加任務
      for(int i = 0; i<10; i++){
         final int task = i;
         threadPool.execute(new Runnable(){
            @Override
            public void run() {
                for(int j = 0 ; j<10 ; j++){
                   try {
                      Thread.sleep(20);
                   } catch (InterruptedException e) {
                      e.printStackTrace();
                   }
                   System.out.println(Thread.currentThread().getName() + " is loop of " + j+
                         " for task " + task);
                }
            }
         });
      }
      System.out.println("all of 10 tasks have committed!");
//    threadPool.shutdownNow();
     
     
      //**********用線程池啓動定時器:
      /**
       * 10s後執行的任務
       */
      Executors.newScheduledThreadPool(3).schedule(
            new Runnable(){
                @Override
                public void run() {
                   System.out.println("bombing!");
                }
            },
            10,
            TimeUnit.SECONDS
      );
     
      /**
       * 程序開始6s後爆炸,然後每隔2s爆炸
       */
      Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
            new Runnable(){
                @Override
                public void run() {
                   System.out.println("bombing");
                  
                }
            },
            6,
            2,
            TimeUnit.SECONDS);
     
   }
}
 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章