原文:http://www.andyqian.com/2018/03/07/java/javaSmallDetail/

前言

今天我们一起来做个简单有趣的实验。熟悉Java的童鞋,对ScheduledExecutorService类应该不陌生。不记得的童鞋,先回忆下。

实验一

我们先看下下面这段简单的代码。如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ExecutoryServiceTest {

        private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);

        public static void main(String[] args){
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
int[] array = new int[1];
System.out.println("<hello world>");
System.out.println(array[1]);
}},0,2, TimeUnit.SECONDS);
}
}

够简单了吧。意思我就不再阐述了。看完别急,我们先回答下面这个问题:

问题一:

请问:上面一共打印了多少个hello world。

实验二

看到此处的童鞋,请在评论区给出你第一个实验的答案。紧接着,我们继续看第二个实验。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class ExecutoryServiceTest {

        private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);

        public static void main(String[] args){
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
int[] array = new int[1];
System.out.println("<hello world>");
System.out.println(array[1]);
}catch(Exception ex){
ex.printStackTrace();
}
}},0,2, TimeUnit.SECONDS);
}
}

问题二:

请问: 实验二中一共打印了多少个<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()方法中也有同样的描述。

一点点建议

  1. 在使用scheduleAtFixedRate()scheduleWithFixedDelay()时,run()方法均要在使用try{}catch处理。避免出现定时任务执行若干次后不执行的”怪现象”。

  2. 我们平时在写系统时,无论是使用JDK自带函数,还是对接外部服务。使用时,一定要了解其使用方法。对入参,结果等都充分理解。(不瞒你说,我就出现过很多次没理解充分。导致Bug产生)。

  3. 强烈建议大家都在本机上运行下上面这实验的代码。这样有利于加深影响。

最新文章

  1. Android开发之Java集合类性能分析
  2. NSURLSessionTask使用dispatch_semaphore 完成同步机制
  3. 初学者对Spring MVC的认识
  4. C#获取当前日期时间(转)
  5. 如何撰写SCI论文的讨论部分?——经典结构 – 俗称“倒漏斗型。
  6. Unity3D研究院之在把代码混淆过的游戏返混淆回来
  7. Shell变量之自定义变量、环境变量
  8. 字符串模式匹配算法——BM、Horspool、Sunday、KMP、KR、AC算法一网打尽
  9. ThreadLocal的使用 .
  10. C#的Split用法
  11. 使用gSoap做一个简单的CS系统
  12. ubuntu配置LAMP
  13. [BZOJ1009] [HNOI2008] GT考试 (KMP &amp; dp &amp; 矩阵乘法)
  14. Docker:Docker 性质及版本选择 [三]
  15. centos6下ActiveMQ+Zookeeper消息中间件集群部署记录
  16. PHP is_numeric 检测变量是否为数字或数字字符串
  17. Linux 压缩归档
  18. C++ 大学课堂知识点总结
  19. Oracle PL/SQL学习之基础篇(1)
  20. jQuery属性操作之.val()函数

热门文章

  1. Django 国内最全教程
  2. 2017多校第9场 HDU 6166 Senior Pan 堆优化Dij
  3. 经典卷积网络模型 — LeNet模型笔记
  4. python 使用国内源安装软件
  5. 1:django models
  6. JVM监控常用命令行工具
  7. Mybatis插入数据返回自增主键
  8. 用淘宝镜像cnpm代替npm
  9. 追忆似水流年sed
  10. Mac安装Maven