定时器& TimerTask与Thread +在Java中的睡眠 [英] Timer & TimerTask versus Thread + sleep in Java
问题描述
我在这里发现了类似的问题,但没有我满意的答案。所以再次重新提出这个问题 -
I found similar questions asked here but there weren't answers to my satisfaction. So rephrasing the question again-
我有一项需要定期完成的任务(比如每隔1分钟)。使用Timertask& amp;定时器执行此操作而不是创建具有无限循环睡眠的新线程?
I have a task that needs to be done on a periodic basis (say 1 minute intervals). What is advantage of using Timertask & Timer to do this as opposed to creating a new thread that has a infinite loop with sleep?
使用timertask的代码片段 -
Code snippet using timertask-
TimerTask uploadCheckerTimerTask = new TimerTask(){
public void run() {
NewUploadServer.getInstance().checkAndUploadFiles();
}
};
Timer uploadCheckerTimer = new Timer(true);
uploadCheckerTimer.scheduleAtFixedRate(uploadCheckerTimerTask, 0, 60 * 1000);
使用线程和睡眠的代码片段 -
Code snippet using Thread and sleep-
Thread t = new Thread(){
public void run() {
while(true) {
NewUploadServer.getInstance().checkAndUploadFiles();
Thread.sleep(60 * 1000);
}
}
};
t.start();
如果逻辑执行需要更多,如果我错过了某些周期,我真的不必担心比间隔时间。
I really don't have to worry if I miss certain cycles if the execution of the logic takes more than the interval time.
请对此发表评论..
更新:
最近我发现使用Timer与Thread.sleep()之间存在另一个区别。假设当前系统时间是上午11:00。如果由于某种原因我们将系统时间回滚到上午10:00,则计时器将停止执行任务,直到它到达上午11:00,而Thread.sleep()方法将继续执行任务而不受阻碍。这可能是决定在这两者之间使用什么的主要决策者。
Update:
Recently I found another difference between using Timer versus Thread.sleep(). Suppose the current system time is 11:00AM. If we rollback the system time to 10:00AM for some reason, The Timer will STOP executing the task until it has reached 11:00AM, whereas Thread.sleep() method would continue executing the task without hindrance. This can be a major decision maker in deciding what to use between these two.
推荐答案
TimerTask的优点在于它表达了你的意图更好(即代码可读性),并且已经实现了cancel()功能。
The advantage of TimerTask is that it expresses your intention much better (i.e. code readability), and it already has the cancel() feature implemented.
请注意,它可以用更短的形式和你自己的形式编写例如:
Note that it can be written in a shorter form as well as your own example:
Timer uploadCheckerTimer = new Timer(true);
uploadCheckerTimer.scheduleAtFixedRate(
new TimerTask() {
public void run() { NewUploadServer.getInstance().checkAndUploadFiles(); }
}, 0, 60 * 1000);
这篇关于定时器& TimerTask与Thread +在Java中的睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!