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中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定