一个Java细节!

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

前言

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

实验一

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

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>

实验二

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

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

最后: 大家晚安

这里写图片描述

 扫码关注,一起进步

个人博客: http://www.andyqian.com

猜你喜欢

转载自my.oschina.net/u/1462914/blog/1630085