Java并发系列 ScheduledExecutorService 使用

2024-05-26 21:32

本文主要是介绍Java并发系列 ScheduledExecutorService 使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文介绍 ScheduledExecutorService 在Java1.5以后才出现的定时任务的,在Java5之后,并发线程这块发生了根本的变化,最重要的莫过于新的启动、调度、管理线程的一大堆API了。定时任务在1.5之前是使用 Timer 来实现的,但由于 Timer 有一些问题:

Timer对调度的支持是基于绝对时间,而不是相对时间的,
由此任务对系统时钟的改变是敏感的;ScheduledThreadExecutor只支持相对时间。
Timer的另一个问题在于,如果TimerTask抛出未检查的异常,Timer将会产生无法预料的行为。
Timer线程并不捕获异常,所以TimerTask抛出的未检查的异常会终止timer线程。
这种情况下,Timer也不会再重新恢复线程的执行了;它错误的认为整个Timer都被取消了。
此时,已经被安排但尚未执行的TimerTask永远不会再执行了,新的任务也不能被调度了。

所以建议使用1.5以后的 ScheduledExecutorService 这个定时服务对象

废话不说直接看代码吧:里面有相应的注释

package task;import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;/**官方文档:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html中文版:http://www.apihome.cn/api/java/ScheduledExecutorService.html*/
public class TaskTest {/*** 线程池的管理工具* 调度型线程池*/private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);/*** 官方案例*/public static void beepForAnHour() {final Runnable beeper = new Runnable() {public void run() {System.out.println("beep");}};final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 100, TimeUnit.MILLISECONDS);scheduler.schedule(new Runnable() {public void run() {System.out.println("cancel");/*** Attempts to cancel execution of this task. This attempt will fail if the task has already completed,* has already been cancelled, or could not be cancelled for some other reason.* If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, * then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.* After this method returns, subsequent calls to isDone() will always return true. Subsequent calls to isCancelled() will always return true if this method returned true.* 试图取消执行这一任务。这种尝试会失败如果任务已经完成,已经被取消了,或者由于其他原因不能被取消。* 如果成功的话,这个任务并没有开始时取消,这个任务不应该运行。如果任务已经开始,那么mayInterruptIfRunning参数决定是否应该中断线程执行这个任务,试图阻止这项任务。* 该方法返回后,后续调用结束()将始终返回true。后续调用isCancelled()将始终返回true,如果这个方法返回true。*/beeperHandle.cancel(true);/***  如果这个任务被取消之前完成正常。*  Returns true if this task was cancelled before it completed normally.*/System.out.println(beeperHandle.isCancelled());}}, 60*60, TimeUnit.MILLISECONDS);}/***  Creates and executes a periodic action that becomes enabled first after the given initial delay, *  and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, *  then initialDelay + 2 * period, and so on. 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. *  If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.*  创建并执行一个周期性的动作成为了第一个在给定的初始延迟之后,随后用给定的时期,这是执行后将开始initialDelay然后initialDelay +,然后initialDelay + 2 *时期,等等。*  如果任何执行任务遇到异常,后续执行的镇压。否则,只会终止的任务通过取消或终止执行器。如果执行这个任务花费的时间比其期,然后后续执行可能会迟到,但不会同时执行。*  command:执行线程*  initialDelay:初始化延时  启动以后多久执行*  period:两次开始执行最小间隔时间 距离上次执行的时间*  unit:计时单位*/public static void scheduleAtFixedRate(){scheduler.scheduleAtFixedRate(new Runnable() {@Overridepublic void run() {System.out.println("scheduleAtFixedRate"+System.currentTimeMillis());}}, 1000, 100, TimeUnit.MILLISECONDS);}public static void main(String[] args) {try {
//			beepForAnHour();
//			scheduleAtFixedRate();scheduleWithFixedDelay();
//			lanuchTimer();
//			Thread.sleep(3000);
//			taskT();
//			Thread.sleep(1000 * 60);
//			studow();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** Creates and executes a periodic action that becomes enabled first after the given initial delay,*  and subsequently with the given delay between the termination of one execution and the commencement of the next. *  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.*  创建并执行一个周期性的动作成为了第一个在给定的初始延迟之后,随后用给定的延迟之间的终止执行和接下来的毕业典礼。如果任何执行任务遇到异常,后续执行的镇压。*  否则,只会终止的任务通过取消或终止执行器。*/public static void scheduleWithFixedDelay() {scheduler.scheduleWithFixedDelay(new Runnable() {public void run() {System.out.println("scheduleWithFixedDelay---->"+System.currentTimeMillis());}}, 1000, 100, TimeUnit.MILLISECONDS);}/*** 关闭执行服务对象*/public static void studow() {scheduler.shutdown();}/*** 凌晨3点钟执行*/public static void taskTimr() {long oneDay = 24 * 60 * 60 * 1000;  long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();  initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;  scheduler.scheduleAtFixedRate(  new EchoServer(),  initDelay,  oneDay,  TimeUnit.MILLISECONDS);  }/** * 获取指定时间对应的毫秒数 * @param time "HH:mm:ss" * @return */  private static long getTimeMillis(String time) {  try {  DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");  DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");  Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);  return curDate.getTime();  } catch (Exception e) {  e.printStackTrace();  }  return 0;  }  }class EchoServer implements Runnable {  @Override  public void run() {  try {  Thread.sleep(50);  } catch (InterruptedException e) {  e.printStackTrace();  }  System.out.println("This is a echo server. The current time is " +  System.currentTimeMillis() + ".");  }  
}  


这篇关于Java并发系列 ScheduledExecutorService 使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1005639

相关文章

Java中对象的创建和销毁过程详析

《Java中对象的创建和销毁过程详析》:本文主要介绍Java中对象的创建和销毁过程,对象的创建过程包括类加载检查、内存分配、初始化零值内存、设置对象头和执行init方法,对象的销毁过程由垃圾回收机... 目录前言对象的创建过程1. 类加载检查2China编程. 分配内存3. 初始化零值4. 设置对象头5. 执行

SpringBoot整合easy-es的详细过程

《SpringBoot整合easy-es的详细过程》本文介绍了EasyES,一个基于Elasticsearch的ORM框架,旨在简化开发流程并提高效率,EasyES支持SpringBoot框架,并提供... 目录一、easy-es简介二、实现基于Spring Boot框架的应用程序代码1.添加相关依赖2.添

通俗易懂的Java常见限流算法具体实现

《通俗易懂的Java常见限流算法具体实现》:本文主要介绍Java常见限流算法具体实现的相关资料,包括漏桶算法、令牌桶算法、Nginx限流和Redis+Lua限流的实现原理和具体步骤,并比较了它们的... 目录一、漏桶算法1.漏桶算法的思想和原理2.具体实现二、令牌桶算法1.令牌桶算法流程:2.具体实现2.1

Python使用Pandas对比两列数据取最大值的五种方法

《Python使用Pandas对比两列数据取最大值的五种方法》本文主要介绍使用Pandas对比两列数据取最大值的五种方法,包括使用max方法、apply方法结合lambda函数、函数、clip方法、w... 目录引言一、使用max方法二、使用apply方法结合lambda函数三、使用np.maximum函数

SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程

《SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程》本文详细介绍了如何在虚拟机和宝塔面板中安装RabbitMQ,并使用Java代码实现消息的发送和接收,通过异步通讯,可以优化... 目录一、RabbitMQ安装二、启动RabbitMQ三、javascript编写Java代码1、引入

spring-boot-starter-thymeleaf加载外部html文件方式

《spring-boot-starter-thymeleaf加载外部html文件方式》本文介绍了在SpringMVC中使用Thymeleaf模板引擎加载外部HTML文件的方法,以及在SpringBoo... 目录1.Thymeleaf介绍2.springboot使用thymeleaf2.1.引入spring

Qt 中集成mqtt协议的使用方法

《Qt中集成mqtt协议的使用方法》文章介绍了如何在工程中引入qmqtt库,并通过声明一个单例类来暴露订阅到的主题数据,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一,引入qmqtt 库二,使用一,引入qmqtt 库我是将整个头文件/源文件都添加到了工程中进行编译,这样 跨平台

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满