zoukankan      html  css  js  c++  java
  • ScheduledExecutorService run方法要加入try catch

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

  • 相关阅读:
    python基础:映射和集合类型
    python基础:列表生成式和生成器
    python基础:名称空间与作用域
    http://www.cnblogs.com/fczjuever/archive/2013/04/05/3000680.html
    2016新年总结
    send()和recv()函数详解
    python基础:测量python代码的运行时间
    python函数与方法装饰器
    Python基础:11.2_函数调用
    MySQL学习笔记-数据库后台线程
  • 原文地址:https://www.cnblogs.com/shihaiming/p/8630135.html
Copyright © 2011-2022 走看看