Java併發newScheduledThreadPool()方法

可以通過調用Executors類的static newScheduledThreadPool()方法獲得一個調度的線程池。

語法

ExecutorService executor = Executors.newScheduledThreadPool(1);

示例

以下TestThread程序顯示了基於線程的環境中newScheduledThreadPool()方法的使用。

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

      final ScheduledFuture<?> beepHandler = 
         scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS);

      scheduler.schedule(new Runnable() {
         @Override
         public void run() {
            beepHandler.cancel(true);'
            scheduler.shutdown();            
         }
      }, 10, TimeUnit.SECONDS);
   }  

   static class BeepTask implements Runnable {
      public void run() {
         System.out.println("beep");      
      }
   }
}

這將產生以下結果 -

beep
beep
beep
beep
beep