Timer ActionListener operation in java

2019-06-25 08:26发布

问题:

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?

回答1:

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!



回答2:

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.)



回答3:

You can test it yourself implementing something as follows:

class TimerActionListener implements ActionListener {
    public static int inst = 1;
    public void actionPerformed(ActionEvent e) {
        int id = inst++;
        System.out.println("Executing instance: " + id);
        try { Thread.sleep(3000); } catch (Exception e) {} //For sleep 3 seconds
        System.out.println("Instance: " + id + "done! ");
    }
}