使用ScheduledThreadPoolExecutor代替TimerTimerTask
如果我们想要延迟(deferred)或者周期性(periodic)执行一个任务,我们可以使用Java API 的Timer和TimerTask类。
一般步骤是:
继承TimerTask(抽象类),复写run方法,方法体里代表需要执行的任务。
实例化Timer(可以通过构造方法设置为守护线程),调用schedule的一个重载方法实现延迟或者周期性执行自定义任务。
下面的例子演示了程序启动5秒后每隔1秒警报器叫一声,10次后终止程序执行。
![](http://201211131343.iteye.com/images/icon_copy.gif)
![](http://201211131343.iteye.com/images/icon_star.png)
![](http://201211131343.iteye.com/images/spinner.gif)
- import java.awt.Toolkit;
- import java.util.Timer;
- import java.util.TimerTask;
- /**
- * 自定义Timer类
- *
- */
- class BeepTimer extends TimerTask {
- private Toolkit toolKit;
- private int count;
- public BeepTimer() {
- toolKit = Toolkit.getDefaultToolkit();
- }
- @Override
- public void run() {
- if (count == 10)
- System.exit(1);
- toolKit.beep();
- count++;
- }
- }
- public class TimerDemo {
- public static void main(String... args) {
- BeepTimer bt = new BeepTimer(); //非守护线程
- Timer timer = new Timer();
- timer.schedule(bt, 5 * 1000, 1 * 1000); // 5秒后开始鸣叫,鸣叫10次,每次相隔1秒钟
- }
- }
import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;/*** 自定义Timer类* */
class BeepTimer extends TimerTask {private Toolkit toolKit;private int count;public BeepTimer() {toolKit = Toolkit.getDefaultToolkit();}@Overridepublic void run() {if (count == 10)System.exit(1);toolKit.beep();count++;}}public class TimerDemo {public static void main(String... args) {BeepTimer bt = new BeepTimer(); //非守护线程Timer timer = new Timer();timer.schedule(bt, 5 * 1000, 1 * 1000); // 5秒后开始鸣叫,鸣叫10次,每次相隔1秒钟}}
但是Timer和TimerTask存在一些缺陷:
1:Timer只创建了一个线程。当你的任务执行的时间超过设置的延时时间将会产生一些问题。
2:Timer创建的线程没有处理异常,因此一旦抛出非受检异常,该线程会立即终止。
JDK 5.0以后推荐使用ScheduledThreadPoolExecutor。该类属于Executor Framework,它除了能处理异常外,还可以创建多个线程解决上面的问题。
下面利用ScheduledThradPoolExecutor实现同一个功能。
![](http://201211131343.iteye.com/images/icon_copy.gif)
![](http://201211131343.iteye.com/images/icon_star.png)
![](http://201211131343.iteye.com/images/spinner.gif)
- import java.awt.Toolkit;
- import java.util.concurrent.ScheduledThreadPoolExecutor;
- import java.util.concurrent.TimeUnit;
- public class ExecutorDemo {
- public static void main(String... args) {
- ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(10);
- MyTask myTask = new MyTask();
- stpe.scheduleWithFixedDelay(myTask, 5,1,TimeUnit.SECONDS);
- }
- private static class MyTask implements Runnable {
- private Toolkit toolKit;
- private int count;
- public MyTask() {
- toolKit = Toolkit.getDefaultToolkit();
- }
- @Override
- public void run() {
- if(count == 10) {
- System.out.println("Termination!");
- System.exit(1);
- }
- toolKit.beep();
- System.out.println("Beep--------");
- count++;
- }
- }
- }
import java.awt.Toolkit;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;public class ExecutorDemo {public static void main(String... args) {ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(10);MyTask myTask = new MyTask();stpe.scheduleWithFixedDelay(myTask, 5,1,TimeUnit.SECONDS);}private static class MyTask implements Runnable {private Toolkit toolKit;private int count;public MyTask() {toolKit = Toolkit.getDefaultToolkit();}@Overridepublic void run() {if(count == 10) {System.out.println("Termination!");System.exit(1);}toolKit.beep();System.out.println("Beep--------");count++;}}
}
转载于:https://www.cnblogs.com/shhaoran/archive/2013/02/05/2924517.html
使用ScheduledThreadPoolExecutor代替TimerTimerTask相关推荐
- ScheduledThreadPoolExecutor()定时执行线程池详解,java线程池
为什么80%的码农都做不了架构师?>>> package com.dy.pool;import java.util.concurrent.ExecutorService; im ...
- ScheduledThreadPoolExecutor详解
2019独角兽企业重金招聘Python工程师标准>>> 本文主要分为两个部分,第一部分首先会对ScheduledThreadPoolExecutor进行简单的介绍,并且会介绍其主要A ...
- ScheduledThreadPoolExecutor的相关知识
转载请标明出处:[顾林海的博客] 个人开发的微信小程序,目前功能是书籍推荐,后续会完善一些新功能,希望大家多多支持! ##前言 ScheduledThreadPoolExecutor继承自Thread ...
- (二十)java多线程之ScheduledThreadPoolExecutor
本人邮箱: <kco1989@qq.com> 欢迎转载,转载请注明网址 http://blog.csdn.net/tianshi_kco github: https://github.co ...
- java定时器返回future_java 定时器线程池(ScheduledThreadPoolExecutor)的实现
前言 定时器线程池提供了定时执行任务的能力,即可以延迟执行,可以周期性执行.但定时器线程池也还是线程池,最底层实现还是ThreadPoolExecutor,可以参考我的另外一篇文章多线程–精通Thre ...
- ScheduledThreadPoolExecutor定时任务线程池执行原理分析
一.示例代码 @Slf4j public class ScheduleThreadPoolTest {private static ScheduledExecutorService executor ...
- 线程池之ScheduledThreadPoolExecutor线程池源码分析笔记
1.ScheduledThreadPoolExecutor 整体结构剖析. 1.1类图介绍 根据上面类图图可以看到Executor其实是一个工具类,里面提供了好多静态方法,根据用户选择返回不同的线程池 ...
- Java并发编程—ScheduledThreadPoolExecutor原理分析
原文作者:小付 原文地址:ScheduledThreadPoolExecutor原理分析 目录 一.简单使用 二.类UML图 三.处理流程 四.任务提交方式 五.SchduledFutureTask之 ...
- java定时线程池_java 定时器线程池(ScheduledThreadPoolExecutor)的实现
前言 定时器线程池提供了定时执行任务的能力,即可以延迟执行,可以周期性执行.但定时器线程池也还是线程池,最底层实现还是ThreadPoolExecutor,可以参考我的另外一篇文章多线程–精通Thre ...
最新文章
- 北航学长:DCIC 2021的算法方案讲解
- 用python画漂亮图片-使用 Python/matplotlib 画出漂亮的论文插图
- 读书笔记:《图解HTTP》第一章 网络基础
- firewall防火墙
- tomcat(supplement)HttpConnector.initialize() 和 start() 方法 以及 StandardContext.start()方法的分析
- centos5.8安装mysql5.3_CentOS 5.8 64位 源码安装mysql5.5.28
- PHP7 网络编程(四)signal信号【待】
- C语言——指针篇(二)指针和数组之内存分配和初始化
- lua中variables和table
- 通过cmd进行文件格式的转换
- ios 判断打开相机权限_ios 判断是否有权限访问相机,相册,定位
- Maven Helper 安装使用
- 51单片机串口通信(自动发送)
- android listview 上拉图片闪烁,android listview使用glide异步加载图片错位,闪烁问题...
- Arduino开发实例-DIY超声波传感器避障机器人
- 有关神经网络的训练算法,深度神经网络训练方法
- Qter 开发资源大集合
- 商用短链平台_第8章_ 账号微服务注册模块+短信验证码+阿里云OSS开发实战
- 王兴,中国互联网最小清新的男人!
- 洛谷 P5197 [USACO19JAN]Grass Planting 题解
热门文章
- pythonweb扫描器_Python安全工具之web目录扫描
- python csv 大文件_Python性能调优:JSON到CSV,大文件
- 数学之美系列五 -- 简单之美:布尔代数和搜索引擎的索引
- .NET Core SignalR Redis底板详解(一)
- C++ 术语(C++ Primer)
- Express框架Restful API Ajax 跨域 开启Cookie支持
- mysql什么情况下使用索引
- 洛谷 P1516 青蛙的约会
- 【tomcat】手动部署动态JavaWeb项目到tomcat
- Dart基础学习03--方法的使用