📜  newScheduledThreadPool方法

📅  最后修改于: 2020-11-15 03:57:50             🧑  作者: Mango


可以通过调用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