Timer和TimerTask详解
2016-01-25 23:01
399 查看
一 · Timer和TimerTask简介
Timer:
官方文档 ——
public class Timer extends Object
Timers schedule one-shot or recurring tasks for execution. Prefer ScheduledThreadPoolExecutor for new code.
Each timer has one thread on which tasks are executed sequentially. When this thread is busy running a task, runnable tasks may be subject to delays.
One-shot are scheduled to run at an absolute time or after a relative delay.
Recurring tasks are scheduled with either a fixed period or a fixed rate:
With the default fixed-period execution, each successive run of a task is scheduled relative to the start time of the previous run, so two runs are never fired closer together in time than the specified period.
With fixed-rate execution, the start time of each successive run of a task is scheduled without regard for when the previous run took place. This may result in a series of bunched-up runs (one launched immediately after another) if delays prevent the timer from starting tasks on time.
When a timer is no longer needed, users should call cancel(), which releases the timer’s thread and other resources. Timers not explicitly cancelled may hold resources indefinitely.
This class does not offer guarantees about the real-time nature of task scheduling. Multiple threads can share a single timer without synchronization.
TimerTask:
官方文档 ——
public abstract class TimerTask extends Object implements Runnable
The TimerTask class represents a task to run at a specified time. The task may be run once or repeatedly.
See Also:
Timer, Object.wait(long)
翻译和总结:
Timer:是一个定时器工具,每一个Timer有一个线程执行任务,当任务过多时,会出现延误。任务可以被多次重复执行。
TimerTask:是一个实现了Runnable接口的抽象类,可以被Timer重复执行。
二 · Timer的例子
这个小程序的输出结果是:
进入应用10秒钟后,开始Toast显示“第*次提示”,每5秒显示一次,不停循环。
Timer执行计划任务的过程:
new一个TimerTask的子类,重写run方法来指定具体的任务,在这个例子里,我用匿名内部类的方式来实现了一个TimerTask的子类。
new一个Timer类,Timer的构造函数里会起一个单独的线程来执行计划任务。
三 · 终止线程
调用cancel()方法(如上面的例子)
cancel( )方法:没有显式的线程stop方法,而是调用了queue的clear方法和queue的notify方法,clear方法将TimerTask数组清空为0,notify( )方法通知Timer中的thread线程的wait( ),清空数组,结束线程。
四 · 循环操作
三个参数:
第一个 —— TimerTask对象的引用;
第二个 —— delay时间(long型),即多长时间后开始执行;
第三个 —— period时间(long型),循环执行的时间间隔;
五 · schedule 和 scheduleAtFixedRate
这两个方法都是任务调度方法,他们之间区别是,schedule会保证任务的间隔是按照定义的period参数严格执行的,如果某一次调度时间比较长,那么后面的时间会顺延,保证调度间隔都是period,而scheduleAtFixedRate是严格按照调度时间来的,如果某次调度时间太长了,那么会通过缩短间隔的方式保证下一次调度在预定时间执行。举个栗子:你每个3秒调度一次,那么正常就是0,3,6,9s这样的时间,如果第二次调度花了2s的时间,如果是schedule,就会变成0,3+2,8,11这样的时间,保证间隔,而scheduleAtFixedRate就会变成0,3+2,6,9,压缩间隔,保证调度时间。
六 · 注意事项
每一个Timer仅对应唯一一个线程。
Timer不保证任务执行的十分精确。
Timer类的线程安全的
参考博客:/article/5602048.html
Timer:
官方文档 ——
public class Timer extends Object
Timers schedule one-shot or recurring tasks for execution. Prefer ScheduledThreadPoolExecutor for new code.
Each timer has one thread on which tasks are executed sequentially. When this thread is busy running a task, runnable tasks may be subject to delays.
One-shot are scheduled to run at an absolute time or after a relative delay.
Recurring tasks are scheduled with either a fixed period or a fixed rate:
With the default fixed-period execution, each successive run of a task is scheduled relative to the start time of the previous run, so two runs are never fired closer together in time than the specified period.
With fixed-rate execution, the start time of each successive run of a task is scheduled without regard for when the previous run took place. This may result in a series of bunched-up runs (one launched immediately after another) if delays prevent the timer from starting tasks on time.
When a timer is no longer needed, users should call cancel(), which releases the timer’s thread and other resources. Timers not explicitly cancelled may hold resources indefinitely.
This class does not offer guarantees about the real-time nature of task scheduling. Multiple threads can share a single timer without synchronization.
TimerTask:
官方文档 ——
public abstract class TimerTask extends Object implements Runnable
The TimerTask class represents a task to run at a specified time. The task may be run once or repeatedly.
See Also:
Timer, Object.wait(long)
翻译和总结:
Timer:是一个定时器工具,每一个Timer有一个线程执行任务,当任务过多时,会出现延误。任务可以被多次重复执行。
TimerTask:是一个实现了Runnable接口的抽象类,可以被Timer重复执行。
二 · Timer的例子
public class MainActivity extends ActionBarActivity { private Timer timer; private TimerTask timerTask; static final int toast=1; int num=1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { timer = new Timer(); timerTask = new TimerTask() { public void run() { handler.sendEmptyMessage(toast); num++; // timer.cancel();//.cancel()方法用于终止线程 } }; timer.schedule(timerTask,10*1000,5*1000); } /** * 使用Handler在异步情况下Toast */ private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case toast: Toast.makeText(MainActivity.this,"第"+num+"次提示",Toast.LENGTH_SHORT).show(); break; default: break; } super.handleMessage(msg); } }; }
这个小程序的输出结果是:
进入应用10秒钟后,开始Toast显示“第*次提示”,每5秒显示一次,不停循环。
Timer执行计划任务的过程:
new一个TimerTask的子类,重写run方法来指定具体的任务,在这个例子里,我用匿名内部类的方式来实现了一个TimerTask的子类。
new一个Timer类,Timer的构造函数里会起一个单独的线程来执行计划任务。
三 · 终止线程
调用cancel()方法(如上面的例子)
public void cancel() { synchronized(queue) { thread.newTasksMayBeScheduled = false; queue.clear(); queue.notify(); // In case queue was already empty. } }
void clear() { // Null out task references to prevent memory leak for (int i=1; i<=size; i++) queue[i] = null; size = 0; }
public Timer() { this("Timer-" + serialNumber()); } public Timer(String name) { thread.setName(name); thread.start(); }
cancel( )方法:没有显式的线程stop方法,而是调用了queue的clear方法和queue的notify方法,clear方法将TimerTask数组清空为0,notify( )方法通知Timer中的thread线程的wait( ),清空数组,结束线程。
四 · 循环操作
timer.schedule(timerTask,10*1000,5*1000);
三个参数:
第一个 —— TimerTask对象的引用;
第二个 —— delay时间(long型),即多长时间后开始执行;
第三个 —— period时间(long型),循环执行的时间间隔;
五 · schedule 和 scheduleAtFixedRate
这两个方法都是任务调度方法,他们之间区别是,schedule会保证任务的间隔是按照定义的period参数严格执行的,如果某一次调度时间比较长,那么后面的时间会顺延,保证调度间隔都是period,而scheduleAtFixedRate是严格按照调度时间来的,如果某次调度时间太长了,那么会通过缩短间隔的方式保证下一次调度在预定时间执行。举个栗子:你每个3秒调度一次,那么正常就是0,3,6,9s这样的时间,如果第二次调度花了2s的时间,如果是schedule,就会变成0,3+2,8,11这样的时间,保证间隔,而scheduleAtFixedRate就会变成0,3+2,6,9,压缩间隔,保证调度时间。
六 · 注意事项
每一个Timer仅对应唯一一个线程。
Timer不保证任务执行的十分精确。
Timer类的线程安全的
参考博客:/article/5602048.html
相关文章推荐
- Extjs4中的Ext.form.field.Spinner
- 大型网站架构 - LAMP
- 87. Scramble String
- 【JS学习笔记】 面向对象与原型
- 图解TCP-IP协议
- LVS-NAT配置
- 做为网址导航生存何在或转行
- 侧边栏滚动条
- kafka入门:简介、使用场景、设计原理、主要配置及集群搭建(转)
- LeetCode 64. Minimum Path Sum
- vmware tools 安装
- Hadoop Shell命令
- 关于Android Studio出现Plugin is too old, please update to a more recent version....问题
- Spring依赖注入:注解注入总结
- 认识JS
- 让LwIP拥有PING其他设备的能力
- 92. Pow(x, n)
- POJ 1936(字符串匹配)
- Linux LVM(逻辑卷管理)
- JAVA 聊天窗口