zoukankan      html  css  js  c++  java
  • 定时线程池

    定时任务ScheduledThreadPoolExecutor:

    1. 介绍:
      之前我们讲的ThreadPoolExecutor是java的普通线程池。而ScheduledThreadPoolExecutor是java提供的定时任务线程池。

    2. 使用:

    常用方法
    java.util.concurrent.ScheduledThreadPoolExecutor#schedule 定时任务
    java.util.concurrent.ScheduledThreadPoolExecutor#scheduleAtFixedRate 固定速率连续执行
    java.util.concurrent.ScheduledThreadPoolExecutor#scheduleWithFixedDelay非固定速率连续执行
    java.util.concurrent.ScheduledThreadPoolExecutor.DelayedWorkQueue延迟队列

    1. scheduleAtFixedRate 和scheduleWithFixedDelay区别
      实例代码:gitee仓库地址
      部分代码
    //测试类
    public class Test {
        public static void main(String[] args) {
            final ScheduleServiceImple scheduleServiceImple = new ScheduleServiceImple();
            scheduleServiceImple.startJob(5);
        }
    }
    
    
    
    public class ScheduleServiceImple implements ScheduledService {
        final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);
    
        @Override
        public void startJob(int seconds) {
            executorService.scheduleAtFixedRate(new Monitor(), 0, seconds, TimeUnit.SECONDS);
            //executorService.scheduleWithFixedDelay(new Monitor(), 0, seconds, TimeUnit.SECONDS);
        }
    
        @Override
        public void shutdown() {
    
        }
    }
    
    
    //执行类
    public class Monitor implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "Start Time" + new Date());
            System.out.println("java.version:" + System.getProperty("java.version"));
            System.out.println("java.class.path:" + System.getProperty("java.class.path"));
            System.out.println("user.dir" + System.getProperty("user.dir"));
            try {
            	//等待5秒结束
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "End Time" + new Date());
            System.out.println("===============");
        }
    }
    
    

    解释:

    固定速率连续执行:延迟时间内没有执行完,任务会启动多个并行执行
    非固定速率连续执行:需要等待任务完成后在进行延迟启动任务

    • scheduleWithFixedDelay
      非固定速率执行

    • scheduleAtFixedRate
      在这里插入图片描述

  • 相关阅读:
    HDU 1013 Digital Roots
    HDU 1290 献给杭电五十周年校庆的礼物
    几何分割问题
    HDU 1222 Wolf and Rabbit
    HDU 1997 汉诺塔VII
    HDU 1443 Joseph
    HTML的标题样式
    HDU 1568 Fibonacci
    Hope
    HDU 1071 The area
  • 原文地址:https://www.cnblogs.com/idcode/p/14551408.html
Copyright © 2011-2022 走看看