计时器Java 中的 TimerTask 与线程 + 睡眠 [英] Timer & TimerTask versus Thread + sleep in Java

查看:36
本文介绍了计时器Java 中的 TimerTask 与线程 + 睡眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里发现了类似的问题,但没有让我满意的答案.所以再次改写这个问题-

I found similar questions asked here but there weren't answers to my satisfaction. So rephrasing the question again-

我有一项需要定期完成的任务(比如间隔 1 分钟).使用 Timertask & 有什么好处?定时器来执行此操作,而不是创建一个具有睡眠无限循环的新线程?

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:00AM,Timer 将停止执行任务,直到它到达 11:00AM,而 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);

这篇关于计时器Java 中的 TimerTask 与线程 + 睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆