ScheduledExecutorService中scheduleAtFixedRate方法的同步

来源:互联网 发布:数据采集与图片处理 编辑:程序博客网 时间:2024/05/05 19:59

因为scheduleAtFixedRate是指定频率执行方法,若方法的执行时间大于指定的间隔时间,将会发生,同一时间点 ,执行方法N 次。

所以需要使用同步方法才确保并发操作的安全性。

import Java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

[java] view plain copy
print?
  1. public class TodoTimer {  
  2.     static Logger log = SimpleLogger.getLogger(TodoTimer.class);  
  3.   
  4.     private TodoTimer() {  
  5.     }  
  6.   
  7.     /** 
  8.      * 定时操作线程 
  9.      */  
  10.     private final static Runnable TodoOperation = new Runnable() {  
  11.         public void run() {  
  12.             try {  
  13.                 semaphore.acquire();  
  14.   
  15.                 TodoManager.operate();  
  16.             } catch (InterruptedException e) {  
  17.                 e.printStackTrace();  
  18.             } finally {  
  19.                 semaphore.release();  
  20.             }  
  21.         }  
  22.     };  
  23.   
  24.     /** 
  25.      * 同步信号量 
  26.      */  
  27.     private static final Semaphore semaphore = new Semaphore(1);  
  28.   
  29.     /** 
  30.      * 定时执行 
  31.      */  
  32.     private static ScheduledExecutorService scheduler = null;  
  33.   
  34.     /** 
  35.      * 启动定时器 
  36.      */  
  37.     public static void start() {  
  38.           
  39.         if (scheduler == null) {  
  40.             scheduler = Executors.newScheduledThreadPool(1);  
  41.               
  42.             synchronized (scheduler) {  
  43.               
  44.                 /* 
  45.                  * TODO 设置定时器启动时间和间隔 
  46.                  */  
  47.                 scheduler.scheduleAtFixedRate(TodoOperation, 2060*5, TimeUnit.SECONDS);  
  48.                 log.debug("启动TODO定时器!");  
  49.             }  
  50.               
  51.         } else {  
  52.             log.warn("TODO定时器正在运行!");  
  53.         }  
  54.           
  55.     }  
  56.   
  57.     /** 
  58.      * 停止定时器 
  59.      */  
  60.     public static void stop() {  
  61.         synchronized (scheduler) {  
  62.             if (scheduler != null && !scheduler.isShutdown()) {  
  63.                 scheduler.shutdown();  
  64.                 scheduler = null;  
  65.                 log.debug("关闭TODO定时器!");  
  66.             }  
  67.         }  
  68.     }  
  69.   
  70.     /** 
  71.      * 重启定时器 
  72.      */  
  73.     public static void restart() {  
  74.         stop();  
  75.         start();  
  76.     }  
  77.   
  78.     /** 
  79.      * 手动触发 
  80.      */  
  81.     public static void trigger() {  
  82.         TodoOperation.run();  
  83.     }  
  84. }  


0 0
原创粉丝点击