Java並行ScheduledThreadPoolExecutor類


java.util.concurrent.ScheduledThreadPoolExecutorThreadPoolExecutor的子類,並且可以額外地排程在給定延遲之後執行的命令,或定期執行。

範例

以下TestThread程式顯示了基於執行緒的環境中ScheduledThreadPoolExecutor介面的使用。

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

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      final ScheduledThreadPoolExecutor scheduler = (ScheduledThreadPoolExecutor)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