java - swing中Timer和TimerTask的区别

标签 java multithreading swing timer

嗨,我正在 GUI 中做一个 java 项目,其中我需要在特定时间过去后更改一些内容,我想知道 Timer 和 TimerTask 类之间的差异,以及它们是否都是线程......也想知道知道 java.util.Timer 和 java.swing.Timer 在这种用途上是否不同? 感谢您的回答

最佳答案

您可以在 API 文档中找到所有答案。 IE。 javax.swing.Timer文档说:

In v 1.3, another Timer class was added to the Java platform: java.util.Timer. Both it and javax.swing.Timer provide the same basic functionality, but java.util.Timer is more general and has more features. The javax.swing.Timer has two features that can make it a little easier to use with GUIs. First, its event handling metaphor is familiar to GUI programmers and can make dealing with the event-dispatching thread a bit simpler. Second, its automatic thread sharing means that you don't have to take special steps to avoid spawning too many threads. Instead, your timer uses the same thread used to make cursors blink, tool tips appear, and so on.

简短的回答是 java.util.Timer 更通用。

此外,如果您检查 API 页面,这些类都不会扩展 Thread。其中一些在内部使用Threads`。

如果你确实需要实现某种计时,我建议使用中央 ScheduledThreadPoolExecutor 。这个计划的执行器比任何计时器都更灵活,而且它为您提供了更多的控制权。

关于java - swing中Timer和TimerTask的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43590527/

相关文章:

java - 在 swing 中将节点从 Jtree 拖到操作系统

java - 将二维 boolean 数组写入和读取 CSV 文件时最简单的方法是什么?

java - 给定一个 WSDL,如何检索有关可用操作的信息?

java - 大负载 OkHTTP 上的流意外结束

java - 为什么不建议同步方法?

c++ - 运行新线程 Qt C++

java - JPanel,调整大小的问题

java - 多个线程持有同一个锁?

java.lang.UnsupportedOperationException : Unrecognized property type: org. hibernate.type.BagType

java - 谁能告诉我为什么我的更改数量按钮没有更改数量?