为什么Java中有两个Timer类(一个在javax.swing下,一个在java.util下)? [英] Why are there two Timer classes in Java(one under javax.swing, one under java.util )?
问题描述
我对此感到很困惑。 Java有两个Timer类,一个在 swing 下,以及一个 util ...为什么就是它?如果我想每Y秒运行一次X,我应该使用哪一个?这是否意味着如果我正在构建GUI我必须使用swing版本来定时器?
I am really confused about this . Java has two Timer classes, one under swing , and one under util ... why is that? Which one should I use if I want to simply run X every Y seconds? Does this mean if I'm building a GUI I have to use the swing version for a timer?
谢谢!
推荐答案
以下是javax.swing.Timer和java.util.Timer之间的区别:
Here is the difference between javax.swing.Timer and java.util.Timer:
javax.swing.Timer
- 适合更简单的情况,使用少量计时器(比如少于十几个)
- 在事件派发线程上运行ActionListener对象
- 可以直接更新GUI,而无需使用EventQueue.invokeLater
- 如果任务完全在事件派发线程中运行(即,如果它没有生成工作线程),那么只有当任务没有时,GUI才会保持响应需要很长时间(比如300毫秒以下)
- suitable for simpler cases, using low numbers of timers (say less than a dozen)
- runs ActionListener objects on the event dispatch thread
- can directly update the GUI, without using EventQueue.invokeLater
- if the task runs entirely in the event dispatch thread (that is, if it does not spawn a worker thread), then the GUI will remain responsive only if the task does not take very long (say under 300 milliseconds)
- 比javax.swing.Timer更具可扩展性,并具有其他调度功能
- 运行TimerTask对象在私人线程上
- 需要使用EventQueue.invokeLater来更新GUI
- 在延迟之后执行一次任务。
例如,工具提示管理器使用Swing计时器来确定何时显示工具提示以及何时隐藏它。 - 重复执行任务。
例如,您可以执行动画或更新显示目标进度的组件。
java.util.Timer
您可以使用Swing计时器两种方式:
You can use Swing timers in two ways:
以下是以上信息 http://www.javapractices.com/topic/TopicAction.do?Id = 160 和 http://docs.oracle.com/ javase / tutorial / uiswing / misc / timer.html
如果我想简单地运行X,我应该使用哪一个Y秒?
Which one should I use if I want to simply run X every Y seconds?
取决于您与之交互的内容。如果您正在与GUI交互,那么使用 javax.swing.Timer
,否则使用 java.util.Timer
。
Depending upon what you are interacting with. If you are interacting with GUI then use javax.swing.Timer
, else use java.util.Timer
.
这是否意味着如果我正在构建GUI我必须使用swing版本
作为计时器?
Does this mean if I'm building a GUI I have to use the swing version for a timer?
是
这篇关于为什么Java中有两个Timer类(一个在javax.swing下,一个在java.util下)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!