博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
(原创)定时线程池中scheduleWithFixedDelay和scheduleAtFixedRate的区别
阅读量:4135 次
发布时间:2019-05-25

本文共 2142 字,大约阅读时间需要 7 分钟。

scheduleAtFixedRate 没有什么歧义,很容易理解,就是每隔多少时间,固定执行任务。

scheduleWithFixedDelay 比较容易有歧义

貌似也是推迟一段时间执行任务,但Oracle的解释如下,delay 的意思是当结束前一个执行后延迟的时间

scheduleWithFixedDelay Parameters:

command - the task to execute

initialDelay - the time to delay first execution

delay - the delay between the termination of one execution and the commencement of the next

unit - the time unit of the initialDelay and delay parameters

scheduleWithFixedDelay 比如当前一个任务结束的时刻,开始结算间隔时间,如0秒开始执行第一次任务,任务耗时5秒,任务间隔时间3秒,那么第二次任务执行的时间是在第8秒开始。

 

import java.util.Date; public class WorkerThread implements Runnable{ private String command;         public WorkerThread(String s){        this.command=s;    }     @Override    public void run() {        System.out.println(Thread.currentThread().getName()+" Start. Time = "+new Date());        processCommand();        System.out.println(Thread.currentThread().getName()+" End. Time = "+new Date());    }     private void processCommand() {        try {            Thread.sleep(5000);        } catch (InterruptedException e) {            e.printStackTrace();        }    }     @Override    public String toString(){        return this.command;    }}

 

 

import java.util.Date;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;  public class ScheduledThreadPool {     public static void main(String[] args) throws InterruptedException {        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);        System.out.println("Current Time = "+new Date());        for(int i=0; i<10; i++){            Thread.sleep(1000);            WorkerThread worker = new WorkerThread("do heavy processing");            //scheduledThreadPool.schedule(worker, 3, TimeUnit.SECONDS);            //scheduledThreadPool.scheduleAtFixedRate(worker, 5, 5, TimeUnit.SECONDS);            scheduledThreadPool.scheduleWithFixedDelay(worker, 5, 3, TimeUnit.SECONDS);        }        Thread.sleep(300000);                 scheduledThreadPool.shutdown();        while(!scheduledThreadPool.isTerminated()){        }        System.out.println("Finished all threads");    } }

 

转载地址:http://bxpvi.baihongyu.com/

你可能感兴趣的文章
python数字逆序输出及多个print输出在同一行
查看>>
苏宁产品经理面经
查看>>
百度产品经理群面
查看>>
去哪儿一面+平安科技二面+hr面+贝贝一面+二面产品面经
查看>>
element ui 弹窗在IE11中关闭时闪现问题修复
查看>>
vue 遍历对象并动态绑定在下拉列表中
查看>>
Vue动态生成el-checkbox点击无法选中的解决方法
查看>>
python __future__
查看>>
MySQL Tricks1
查看>>
python 变量作用域问题(经典坑)
查看>>
pytorch
查看>>
pytorch(三)
查看>>
ubuntu相关
查看>>
C++ 调用json
查看>>
nano中设置脚本开机自启动
查看>>
动态库调动态库
查看>>
Kubernetes集群搭建之CNI-Flanneld部署篇
查看>>
k8s web终端连接工具
查看>>
手绘VS码绘(一):静态图绘制(码绘使用P5.js)
查看>>
手绘VS码绘(二):动态图绘制(码绘使用Processing)
查看>>