Java中的Timer ActionListener操作 [英] Timer ActionListener operation in java

查看:390
本文介绍了Java中的Timer ActionListener操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java比较陌生,并且对ActionListeners的工作方式很好奇。假设我有一个计时器的操作侦听器,实现如下:

  class TimerActionListener实现ActionListener 
{
public void actionPerformed(ActionEvent e)
{
//执行某些操作
}
}

如果将计时器设置为比我的actionlistener类中的代码可以执行的速度更快,将会发生什么。代码是否完成执行并忽略新请求,直到完成为止(如中断)。还是对actionlistener的新调用优先于当前实例-这样代码将永远无法完成?

解决方案

计时器的计时在与事件分发线程(或EDT)不同的线程中完成,事件分发线程是在ActionListener中运行代码的线程。因此,即使actionPerformed代码很慢,计时器也将继续触发并在事件队列上排队其actionPerformed代码,这很可能会被备份并且事件线程将被阻塞并且应用程序将无响应或响应速度较慢。 / p>

一个要点是避免在事件线程上调用花费一些时间的任何代码,因为这会使GUI无响应。考虑在这种情况下使用SwingWorker。



编辑:请参见下面的垃圾桶评论,以获取胜利!


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?

解决方案

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!

这篇关于Java中的Timer ActionListener操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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