一个Java细节!

本文首发于我的微信公众号《andyqian》,期待你的关注!

前言

  今天咱们一块儿来作个简单有趣的实验。熟悉Java的童鞋,对ScheduledExecutorService 类应该不陌生。不记得的童鞋,先回忆下。微信

实验一

咱们先看下下面这段简单的代码。以下:ide

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>spa

实验二

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

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>。code

请在评论区中给出你的答案。blog

分析

  通过上述两个实验后,咱们会发现二者的答案并不相同。这是为何呢?由于在:run()方法中,发生异常后,中断了后续的执行。这是为何呢?图片

其实呀,早在:scheduleAtFixedRate()JDK源码中就有这么一段描述:get

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. 强烈建议你们都在本机上运行下上面这两段实验的代码。这样有利于加深印象。

最后: 你们晚安

这里写图片描述

 扫码关注,一块儿进步

我的博客: http://www.andyqian.com

相关文章
相关标签/搜索