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
      在这里插入图片描述

  • 相关阅读:
    Vue生命周期总结
    jQuery的层级选择器
    jQuery操作DOM的相关方法
    PHP基本语法
    组件间的传值
    MV*模式
    js 常用事件
    kali使用-WIFI破解
    使用css将网页变成黑白色
    css权重等级
  • 原文地址:https://www.cnblogs.com/idcode/p/14551408.html
Copyright © 2011-2022 走看看