且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java在新线程上运行javax.swing.Timer?

更新时间:2023-12-03 23:01:10

尽管所有计时器都使用单个共享线程(由执行的第一个Timer对象创建)执行等待,但计时器的操作事件处理程序在另一个线程上执行 - 事件调度线程。这意味着Timers的操作处理程序可以安全地对Swing组件执行操作。但是,这也意味着处理程序必须快速执行以保持GUI响应。 - javax.swing.Timer

"Although all Timers perform their waiting using a single, shared thread (created by the first Timer object that executes), the action event handlers for Timers execute on another thread -- the event-dispatching thread. This means that the action handlers for Timers can safely perform operations on Swing components. However, it also means that the handlers must execute quickly to keep the GUI responsive."—javax.swing.Timer

强调增加。

附录: SwingWorker 是为这种情况而设计的。特别是,它提供了一种方便的卸载工作方式,同时定期在EDT上重建进度。

Addendum: SwingWorker was designed for just this scenario. In particular, it offers a convenient way to offload work while periodically reporing progress on the EDT.