Cyh的博客

          Email:kissyan4916@163.com
          posts - 26, comments - 19, trackbacks - 0, articles - 220

          線程--任務執行架構

          Posted on 2009-12-22 20:53 啥都寫點 閱讀(559) 評論(0)  編輯  收藏 所屬分類: J2SE
              Executor服務對象是用來執行Runnable任務的,常用的方法如下:
                    execute方法用于執行Ruannable類型的任務。
              ExecutorService服務對象能執行和終止Callable任務,它繼承了Executor,所以也能執行Runnable任務。常用的方法如下:

                    submit方法用來提交Callable 或Runnable任務,并返回代表此任務的Future對象。
                    invokeAll方法批處理任務集合,并返回一個代表這些任務的Future對象集合。
                    shutdown方法在完成已提交的任務后關閉服務,不再接受新任務。
                    shutdownNow方法停止所有正在執行的任務并關閉服務。
                    isTerminated測試是否所有任務都執行完畢了。
                    isShuttdown測試是否該ExecutorService已被關閉。

              ScheduledExecutorService服務對象繼承ExecutorService,提供了按時間安排執行任務的功能。常用的方法如下:
                     a>schedule(task,initDelay)方法安排所提交的Runnable任務按指定的間隔重復執行。
                     b>scheduleAtFixedRate方法安排所提交的Runnable任務按指定的間隔重復執行。
                     c>sheduleWithFixedDelay方法安排所提交的Runnable任務在每次執行完后,等待delay所指定的時間后重復執行。
              Executors類用來創建各種服務對象,常用的方法如下:
                     a> callable(Runnable task)方法將Runnable的任務轉化成Callable的任務。
                     b> newSingleThreadExecutor方法產生一個ExecutorService對象,這個對象只有一個線程可用來執行任務,若任務多于一個,則按先后順序執行任務。
                     c>newCachedThreadPool方法產生一個ExecutorService對象,這個對象帶有一個線程池,線程池的大小會根據需要調整,線程執行完任務后返回線程池,供執行下一次任務使用。
                     d>newFixedThreadPool(int poolSize)方法產生一個ExecutorService對象,這個對象帶有一個大小為poolSize的線程池,若任務數量大于poolSize,任務會被放在一個隊列里順序執行
                     e>   newSingleThreadScheduledExecutor方法產生一個ScheduledExecutorService對象,這個對象的線程池大小為1,若任務多余一個,任務將按先后順序執行。
                     f>newScheduledThreadPool(int poolSize) 方法產生一個ScheduleExecutorService對象,這個對象的線程池大小為poolSize,若任務數量大于poolSize,任務會在一個隊列里等待執行。


          import java.util.concurrent.Callable;
          import java.util.concurrent.ExecutionException;
          import java.util.concurrent.ExecutorService;
          import java.util.concurrent.Executors;
          import java.util.concurrent.Future;
          import java.util.concurrent.ScheduledExecutorService;
          import java.util.concurrent.TimeUnit;

          /**
           * 新的任務執行架構。
           * 在Java 5.0之前啟動一個任務是通過調用Thread類的start()方法來實現的,
           * 任務的提于交和執行是同時進行的,如果你想對任務的執行進行調度,
           * 或是控制同時執行的線程數量就需要額外編寫代碼來完成。
           * 5.0里提供了一個新的任務執行架構使你可以輕松地調度和控制任務的執行,
           * 并且可以建立一個類似數據庫連接池的線程池來執行任務。
           * 這個架構主要有三個接口和其相應的具體類組成。
           * 這三個接口是Executor, ExecutorService和ScheduledExecutorService。
           * (1)Executor接口:是用來執行Runnable任務的,它只定義一個方法:
           * execute(Runnable command):執行Ruannable類型的任務
           * (2)ExecutorService:繼承了Executor的方法,并提供了執行Callable任務和中止任務執行的服務,
           * 其定義的方法主要有:
           * submit(task):可用來提交Callable或Runnable任務,并返回代表此任務的Future對象 
           * invokeAll(collection of tasks):批處理任務集合,并返回一個代表這些任務的Future對象集合 
           * shutdown():在完成已提交的任務后關閉服務,不再接受新任務 
           * shutdownNow():停止所有正在執行的任務并關閉服務。 
           * isTerminated():測試是否所有任務都執行完畢了。 
           * isShutdown():測試是否該ExecutorService已被關閉
           * (3)ScheduledExecutorService:繼承ExecutorService,提供了按時間安排執行任務的功能、
           * schedule(task, initDelay): 安排所提交的Callable或Runnable任務在initDelay指定的時間后執行。
           * scheduleAtFixedRate():安排所提交的Runnable任務按指定的間隔重復執行 
           * scheduleWithFixedDelay():安排所提交的Runnable任務在每次執行完后,等待delay所指定的時間后重復執行。
           * 
           * 通過Executors類來獲得各種服務對象。
           * callable(Runnable task): 將Runnable的任務轉化成Callable的任務 
           * newSingleThreadExecutor: 產生一個ExecutorService對象,這個對象只有一個線程可用來執行任務,若任務多于一個,任務將按先后順序執行。 
           * newCachedThreadPool(): 產生一個ExecutorService對象,這個對象帶有一個線程池,線程池的大小會根據需要調整,線程執行完任務后返回線程池,供執行下一次任務使用。
           * newFixedThreadPool(int poolSize):產生一個ExecutorService對象,這個對象帶有一個大小為poolSize的線程池,若任務數量大于poolSize,任務會被放在一個queue里順序執行。 
           * newSingleThreadScheduledExecutor:產生一個ScheduledExecutorService對象,這個對象的線程池大小為1,若任務多于一個,任務將按先后順序執行。 
           * newScheduledThreadPool(int poolSize): 產生一個ScheduledExecutorService對象,這個對象的線程池大小為poolSize,若任務數量大于poolSize,任務會在一個queue里等待執行 
           
          */

          public class ExecuteArch {
              
              
          /**
               * 該線程輸出一行字符串
               
          */

              
          public static class MyThread implements Runnable {
                  
          public void run() {
                      System.out.println(
          "Task repeating. " + System.currentTimeMillis());
                      
          try {
                          Thread.sleep(
          1000);
                      }
           catch (InterruptedException e) {
                          System.out.println(
          "Task interrupted. "
                                  
          + System.currentTimeMillis());
                      }

                  }

              }


              
          /**
               * 該Callable結束另一個任務
               
          */

              
          public static class MyCallable implements Callable {
                  
          private Future future;

                  
          public MyCallable(Future future) {
                      
          this.future = future;
                  }


                  
          public String call() {
                      System.out.println(
          "To cancell Task"
                              
          + +System.currentTimeMillis());
                      
          this.future.cancel(true);
                      
          return "Task cancelled!";
                  }

              }


              
          /**
               * 
          @param args
               * 
          @throws ExecutionException 
               * 
          @throws InterruptedException 
               
          */

              
          public static void main(String[] args) throws InterruptedException,
                      ExecutionException 
          {
                  
          // 產生一個ExecutorService對象,這個對象帶有一個線程池,線程池的大小會根據需要調整,
                  
          // 線程執行完任務后返回線程池,供執行下一次任務使用。
                  ExecutorService cachedService = Executors.newCachedThreadPool();
                  Future myThreadFuture 
          = cachedService.submit(new MyThread());
                  Future myCallableFuture 
          = cachedService.submit(new MyCallable(
                          myThreadFuture));
                  System.out.println(myCallableFuture.get());
                  System.out.println(
          "-----------------");

                  
          // 將Runnable任務轉換成Callable任務
                  Callable myThreadCallable = Executors.callable(new MyThread());
                  Future myThreadCallableFuture 
          = cachedService.submit(myThreadCallable);
                  
          // 對于Runnable任務,轉換成Callable任務后,也沒有返回值
                  System.out.println(myThreadCallableFuture.get());
                  cachedService.shutdownNow();
                  System.out.println(
          "-----------------");

                  
          // 產生一個ExecutorService對象,這個對象帶有一個大小為poolSize的線程池,
                  
          // 若任務數量大于poolSize,任務會被放在一個queue里順序執行
                  ExecutorService fixedService = Executors.newFixedThreadPool(2);
                  fixedService.submit(
          new MyThread());
                  fixedService.submit(
          new MyThread());
                  
          // 由于線程池大小為2,所以后面的任務必須等待前面的任務執行完后才能被執行。
                  myThreadFuture = fixedService.submit(new MyThread());
                  myCallableFuture 
          = fixedService.submit(new MyCallable(myThreadFuture));
                  System.out.println(myCallableFuture.get());
                  fixedService.shutdownNow();
                  System.out.println(
          "-----------------");

                  
          // 產生一個ScheduledExecutorService對象,這個對象的線程池大小為poolSize,
                  
          // 若任務數量大于poolSize,任務會在一個queue里等待執行
                  ScheduledExecutorService fixedScheduledService = Executors
                          .newScheduledThreadPool(
          2);
                  
          // 新建任務1
                  MyThread task1 = new MyThread();
                  
          // 使用任務執行服務立即執行任務1,而且此后每隔2秒執行一次任務1。
                  myThreadFuture = fixedScheduledService.scheduleAtFixedRate(task1, 02,
                          TimeUnit.SECONDS);
                  
          // 新建任務2
                  MyCallable task2 = new MyCallable(myThreadFuture);
                  
          // 使用任務執行服務等待5秒后執行任務2,執行它后會將任務1關閉。
                  myCallableFuture = fixedScheduledService.schedule(task2, 5,
                          TimeUnit.SECONDS);
                  System.out.println(myCallableFuture.get());
                  fixedScheduledService.shutdownNow();
              }

          }




                                                                                                                 --    學海無涯
                  

          主站蜘蛛池模板: 龙门县| 石河子市| 秦安县| 拜泉县| 垫江县| 巴彦淖尔市| 雷波县| 筠连县| 尚志市| 凤庆县| 庆云县| 洛南县| 雷波县| 泽普县| 杭锦后旗| 乌兰浩特市| 萝北县| 泽州县| 依兰县| 咸宁市| 南江县| 万山特区| 湾仔区| 仁布县| 苗栗市| 清原| 横山县| 台湾省| 罗田县| 滨州市| 二连浩特市| 丽水市| 墨江| 西贡区| 周口市| 陵川县| 济宁市| 珲春市| 开原市| 大洼县| 常熟市|