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

相关文章

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

java中新生代和老生代的关系说明

《java中新生代和老生代的关系说明》:本文主要介绍java中新生代和老生代的关系说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、内存区域划分新生代老年代二、对象生命周期与晋升流程三、新生代与老年代的协作机制1. 跨代引用处理2. 动态年龄判定3. 空间分

Java设计模式---迭代器模式(Iterator)解读

《Java设计模式---迭代器模式(Iterator)解读》:本文主要介绍Java设计模式---迭代器模式(Iterator),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录1、迭代器(Iterator)1.1、结构1.2、常用方法1.3、本质1、解耦集合与遍历逻辑2、统一

Java内存分配与JVM参数详解(推荐)

《Java内存分配与JVM参数详解(推荐)》本文详解JVM内存结构与参数调整,涵盖堆分代、元空间、GC选择及优化策略,帮助开发者提升性能、避免内存泄漏,本文给大家介绍Java内存分配与JVM参数详解,... 目录引言JVM内存结构JVM参数概述堆内存分配年轻代与老年代调整堆内存大小调整年轻代与老年代比例元空