ScheduledExecutorService run方法要加入try catch
原文:http://www.andyqian.com/2018/03/07/java/javaSmallDetail/
前言
今天我们一起来做个简单有趣的实验。熟悉Java的童鞋,对ScheduledExecutorService类应该不陌生。不记得的童鞋,先回忆下。
实验一
我们先看下下面这段简单的代码。如下:
1 |
public class ExecutoryServiceTest { private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10); public static void main(String[] args){ |
够简单了吧。意思我就不再阐述了。看完别急,我们先回答下面这个问题:
问题一:
请问:上面一共打印了多少个hello world。
实验二
看到此处的童鞋,请在评论区给出你第一个实验的答案。紧接着,我们继续看第二个实验。
1 |
public class ExecutoryServiceTest { private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10); public static void main(String[] args){ |
问题二:
请问: 实验二中一共打印了多少个<hello world>
。
请在评论区中给出你的答案。
分析
经过上述两个实验后,我们会发现两者的答案并不相同。这是为什么呢?因为在:run()
方法中,发生异常后,中断了后续的执行。这是为什么呢?
其实呀,早在:scheduleAtFixedRate()
JDK源码中就有这么一段描述:
If any execution of the task encounters an exception, subsequent executions are suppressed.Otherwise, the task will only terminate via cancellation or termination of the executor.
其意思就是告诉我们:如果任何执行任务遇到异常,其后续的操作会被压制。
同样的,在scheduleWithFixedDelay()
方法中也有同样的描述。
一点点建议
在使用
scheduleAtFixedRate()
或scheduleWithFixedDelay()
时,run()
方法均要在使用try{}catch
处理。避免出现定时任务执行若干次后不执行的”怪现象”。我们平时在写系统时,无论是使用JDK自带函数,还是对接外部服务。使用时,一定要了解其使用方法。对入参,结果等都充分理解。(不瞒你说,我就出现过很多次没理解充分。导致Bug产生)。
强烈建议大家都在本机上运行下上面这实验的代码。这样有利于加深影响。
最新文章
- Android开发之Java集合类性能分析
- NSURLSessionTask使用dispatch_semaphore 完成同步机制
- 初学者对Spring MVC的认识
- C#获取当前日期时间(转)
- 如何撰写SCI论文的讨论部分?——经典结构 – 俗称“倒漏斗型。
- Unity3D研究院之在把代码混淆过的游戏返混淆回来
- Shell变量之自定义变量、环境变量
- 字符串模式匹配算法——BM、Horspool、Sunday、KMP、KR、AC算法一网打尽
- ThreadLocal的使用 .
- C#的Split用法
- 使用gSoap做一个简单的CS系统
- ubuntu配置LAMP
- [BZOJ1009] [HNOI2008] GT考试 (KMP &; dp &; 矩阵乘法)
- Docker:Docker 性质及版本选择 [三]
- centos6下ActiveMQ+Zookeeper消息中间件集群部署记录
- PHP is_numeric 检测变量是否为数字或数字字符串
- Linux 压缩归档
- C++ 大学课堂知识点总结
- Oracle PL/SQL学习之基础篇(1)
- jQuery属性操作之.val()函数