java中定时器ActionListener操作
我对 java 比较陌生,对 ActionListener 的工作原理很好奇。假设我有一个计时器的动作侦听器,实现如下:
class TimerActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//perform some operation
}
}
如果计时器设置为运行速度快于我的动作侦听器类中的代码执行速度,将会发生什么。代码是否完成执行并忽略新请求直到完成(如中断)。或者对 actionlistener 的新调用是否优先于当前实例 - 这样代码将永远不会完成?
I am relatively new to java and was curious about how ActionListeners work. Say I have an action listener for a timer implemented as follows:
class TimerActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//perform some operation
}
}
What will happen if the timer is set to run faster than the code in my actionlistener class can execute. Does the code finish executing and ignore new requests until it is done (like an interrupt). Or does the new call to actionlistener take priority over the current instance - such that the code will never complete?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
计时器的计时是在与事件分派线程(或 EDT)不同的线程中完成的,事件分派线程是在 ActionListener 中运行代码的线程。因此,即使 actionPerformed 代码很慢,计时器也会继续触发,并将其 actionPerformed 代码放入事件队列中,这可能会被备份,事件线程将被堵塞,应用程序将无响应或响应不良。
值得注意的一点是避免调用任何在事件线程上花费一些时间的代码,因为这会使 GUI 无响应。对于此类情况,请考虑使用 SwingWorker。
编辑:请参阅下面垃圾神的评论以获得胜利!
The timer's timing is done in thread distinct from the event dispatch thread (or EDT) which is the thread that runs the code in the ActionListener. So even if the actionPerformed code is slow, the timer will keep on firing regardless and will queue its actionPerformed code on the event queue which will likely get backed up and the event thread will get clogged and the application will be unresponsive or poorly responsive.
A take-home point is to avoid calling any code that takes a bit of time on the event thread as it will make the GUI unresponsive. Consider using a SwingWorker for cases like this.
Edit: Please see trashgod's comment below for the win!
根据气垫船和垃圾神的帖子,计时器事件似乎不会按默认设置排队。 (即新的计时器事件将被忽略,直到计时器事件处理程序代码完成执行。)
Based on the posts from hovercraft and trashgod, it seems that the Timer events do not queue by their default setting. (i.e. new timer events will be ignored until the timer event handler code has finished executing.)
您可以自己测试一下,实施如下:
You can test it yourself implementing something as follows: