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

相关文章

使用FileChannel实现文件的复制和移动方式

《使用FileChannel实现文件的复制和移动方式》:本文主要介绍使用FileChannel实现文件的复制和移动方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录使用 FileChannel 实现文件复制代码解释使用 FileChannel 实现文件移动代码解释

Spring实现Bean的初始化和销毁的方式

《Spring实现Bean的初始化和销毁的方式》:本文主要介绍Spring实现Bean的初始化和销毁的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、Bean的初始化二、Bean的销毁总结在前面的章节当中介绍完毕了ApplicationContext,也就

Java的"伪泛型"变"真泛型"后对性能的影响

《Java的伪泛型变真泛型后对性能的影响》泛型擦除本质上就是擦除与泛型相关的一切信息,例如参数化类型、类型变量等,Javac还将在需要时进行类型检查及强制类型转换,甚至在必要时会合成桥方法,这篇文章主... 目录1、真假泛型2、性能影响泛型存在于Java源代码中,在编译为字节码文件之前都会进行泛型擦除(ty

Java中的getBytes()方法使用详解

《Java中的getBytes()方法使用详解》:本文主要介绍Java中getBytes()方法使用的相关资料,getBytes()方法有多个重载形式,可以根据需要指定字符集来进行转换,文中通过代... 目录前言一、常见重载形式二、示例代码三、getBytes(Charset charset)和getByt

Java使用Stream流的Lambda语法进行List转Map的操作方式

《Java使用Stream流的Lambda语法进行List转Map的操作方式》:本文主要介绍Java使用Stream流的Lambda语法进行List转Map的操作方式,具有很好的参考价值,希望对大... 目录背景Stream流的Lambda语法应用实例1、定义要操作的UserDto2、ListChina编程转成M

Spring框架中@Lazy延迟加载原理和使用详解

《Spring框架中@Lazy延迟加载原理和使用详解》:本文主要介绍Spring框架中@Lazy延迟加载原理和使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、@Lazy延迟加载原理1.延迟加载原理1.1 @Lazy三种配置方法1.2 @Component

使用easy connect之后,maven无法使用,原来需要配置-Djava.net.preferIPv4Stack=true问题

《使用easyconnect之后,maven无法使用,原来需要配置-Djava.net.preferIPv4Stack=true问题》:本文主要介绍使用easyconnect之后,maven无法... 目录使用easGWowCy connect之后,maven无法使用,原来需要配置-DJava.net.pr

idea报错java: 非法字符: ‘\ufeff‘的解决步骤以及说明

《idea报错java:非法字符:‘ufeff‘的解决步骤以及说明》:本文主要介绍idea报错java:非法字符:ufeff的解决步骤以及说明,文章详细解释了为什么在Java中会出现uf... 目录BOM是什么?1. BOM的作用2. 为什么会出现 \ufeff 错误?3. 如何解决 \ufeff 问题?最

使用Java编写一个字符脱敏工具类

《使用Java编写一个字符脱敏工具类》这篇文章主要为大家详细介绍了如何使用Java编写一个字符脱敏工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、字符脱敏工具类2、测试工具类3、测试结果1、字符脱敏工具类import lombok.extern.slf4j.Slf4j

Java实现按字节长度截取字符串

《Java实现按字节长度截取字符串》在Java中,由于字符串可能包含多字节字符,直接按字节长度截取可能会导致乱码或截取不准确的问题,下面我们就来看看几种按字节长度截取字符串的方法吧... 目录方法一:使用String的getBytes方法方法二:指定字符编码处理方法三:更精确的字符编码处理使用示例注意事项方