2018-08-02

Java 线程时中的两种定时用法

    ScheduledExecutorService sche = Executors.newScheduledThreadPool(5);
    #使用scheduleAtFixedRate方法
    sche.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            System.out.println(new Date());
            try{
                Thread.sleep(3000);
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    },1,2,TimeUnit.SECONDS);
    
    #使用scheduleWithFixedDelay方法
    sche.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            System.out.println(new Date());
            try{
                Thread.sleep(3000);
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    },1,2,TimeUnit.SECONDS);

使用scheduleAtFixedRate方法结果如下

Thu Aug 02 11:01:48 CST 2018
Thu Aug 02 11:01:53 CST 2018
Thu Aug 02 11:01:58 CST 2018
Thu Aug 02 11:02:03 CST 2018

由此可见 scheduleAtFixedRate()方法,当run方法运行时间超过我所定义的2秒,也会继续等待2秒执行,否则 按2秒定时固定执行

使用scheduleAtFixedRate方法结果如下

Thu Aug 02 11:02:41 CST 2018
Thu Aug 02 11:02:44 CST 2018
Thu Aug 02 11:02:47 CST 2018
Thu Aug 02 11:02:50 CST 2018

由此可见 scheduleAtFixedRate()方法,是固定每2秒运行一次,如果run()方法执行时间超过2秒,就立马进入下一次的2秒执行,否则,按2秒定时固定执行

你可能感兴趣的:(2018-08-02)