ScheduledExecutorService中scheduleAtFixedRate方法同步
2016-05-20 11:25
381 查看
由于ScheduledExecutorServices.cheduleAtFixedRate是指定频率执行方法,若方法的执行时间大于指定的间隔时间,将可能会发生,同一时间点 ,执行方法N 次。
所以需要使用同步方法才确保并发操作的安全性。
所以需要使用同步方法才确保并发操作的安全性。
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class TodoTimer { static Logger log = SimpleLogger.getLogger(TodoTimer.class); private TodoTimer() { } /** * 定时操作线程 */ private final static Runnable TodoOperation = new Runnable() { public void run() { try { semaphore.acquire(); TodoManager.operate(); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } } }; /** * 同步信号量 */ private static final Semaphore semaphore = new Semaphore(1); /** * 定时执行 */ private static ScheduledExecutorService scheduler = null; /** * 启动定时器 */ public static void start() { if (scheduler == null) { scheduler = Executors.newScheduledThreadPool(1); synchronized (scheduler) { /* * TODO 设置定时器启动时间和间隔 */ scheduler.scheduleAtFixedRate(TodoOperation, 20, 60*5, TimeUnit.SECONDS); log.debug("启动TODO定时器!"); } } else { log.warn("TODO定时器正在运行!"); } } /** * 停止定时器 */ public static void stop() { synchronized (scheduler) { if (scheduler != null && !scheduler.isShutdown()) { scheduler.shutdown(); scheduler = null; log.debug("关闭TODO定时器!"); } } } /** * 重启定时器 */ public static void restart() { stop(); start(); } /** * 手动触发 */ public static void trigger() { TodoOperation.run(); } }
相关文章推荐
- Github发布了为桌面应用开发而生的Electron 1.0版本(HTML、CSS和JavaScript)
- 有关ScrollView的一些总结
- Android 中的线程池
- python学习小记1
- AngularJS实现跨域请求
- jQuery Ajax与prototypeJS Ajax数据获取的方式
- Android M 新的运行时权限开发者需要知道的一切
- 【Win 10 应用开发】通过数据绑定更新进度条
- 正则表达式应用
- [Delphi]接口认识
- python爬虫
- 二维码zBar之乱码解决
- hdu 5199 Comparison of Android version
- STL中关于map和set的四个问题?
- ASP.NET跨平台实践:无需安装Mono的Jexus“独立版”
- Git 常用命令整理
- iOS避免键盘遮挡输入方案
- JavaScript-学习一全局变量
- sprint1
- LeetCode-215.Kth Largest Element in an Array