java等待swing.timer任务在执行下一个任务之前完成

时间:2017-01-15 01:49:21

标签: java swing timer wait activity-finish

所以标题真的说明了一切。 在执行方法中的下一个命令之前,我需要线程等待计时器完成。

代码:

import javax.swing.Timer;

public class doesntMatter
{
    Timer timer;
    ActionListener timerTask;

    public doesntMatter
    {
         timerTask = new ActionListener()
         {
              @Override
              public void actionPerformed(ActionEvent e)
              {
                  //taskSomethingIdk
              }
         }
    }

    private void whatever
    {
        timer = new Timer(1000, timerTask);
        timer.setInitialDelay(0);
        timer.start();

        // here i need to wait for the timer to finish

        if(timerhasfrigginfinished)
             continueOrSomethingIdk
    }

}

2 个答案:

答案 0 :(得分:1)

假设您的计时器重复,在Timer的ActionListener内部检查它是否正在运行其最后一次重复,如果是,那里,请调用continueOrSomethingIdk()方法。

否则您将不得不设置自己的通知机制,即回调,以便计时器通知任何听众已完成运行。

例如:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

@SuppressWarnings("serial")
public class WhenTimerDone extends JPanel {
    private static final Color[] COLORS = { 
            Color.RED, Color.ORANGE, 
            Color.YELLOW, Color.GREEN,
            Color.BLUE, Color.CYAN };
    private static final String START = "Start";
    private static final String DONE = "Done";
    private static final int PREF_W = 400;
    private static final int PREF_H = PREF_W;
    public static final int TIMER_DELAY = 1000;
    private JLabel statusLabel = new JLabel(START);
    private StartAction startAction = new StartAction("Start!");

    public WhenTimerDone() {
        add(statusLabel);
        add(new JButton(startAction));
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    // this is the method called by the Timer's ActionListener when it is done
    public void done() {
        // reset all to baseline state
        statusLabel.setText(DONE);
        startAction.setEnabled(true);
        setBackground(null);
    }

    // ActionListener for the start button
    private class StartAction extends AbstractAction {

        public StartAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // disables itself
            setEnabled(false);
            statusLabel.setText(START); // updates the status label

            // create and start a timer
            Timer timer = new Timer(TIMER_DELAY, new TimerListener());
            timer.setInitialDelay(0);
            timer.start();    
        }
    }

    // action listener for the timer
    private class TimerListener implements ActionListener {
        private int colorsIndex = 0;

        @Override
        public void actionPerformed(ActionEvent e) {
            // simply loops through a colors array, changing background color
            if (colorsIndex < COLORS.length) {
                setBackground(COLORS[colorsIndex]);
                colorsIndex++;
            } else {
                // when all colors shown -- stop the timer
                ((Timer) e.getSource()).stop();

                // and call the done method -- ******* here's the key!
                done();  // called when Timer is done!
            }
        }
    }

    private static void createAndShowGui() {
        WhenTimerDone mainPanel = new WhenTimerDone();

        JFrame frame = new JFrame("WhenTimerDone");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

答案 1 :(得分:0)

这里的关键字是通知/等待 您的计时器线程应该通知应该等待的其他线程 像这样:

import javax.swing.Timer;

public class doesntMatter
{
Timer timer;
ActionListener timerTask;

public doesntMatter
{
     timerTask = new ActionListener()
     {
          @Override
          public void actionPerformed(ActionEvent e)
          {
              synchronized(timer){
                  //taskSomethingIdk
                  //you would have to rig something so we can access a common object as the monitor/lock object
                  timer.notify()
              }
          }
     }
}

private void whatever
{
    timer = new Timer(1000, timerTask);
    timer.setInitialDelay(0);
    timer.start();
    //Need to obtain a lock on the "monitor" object
    //Lock will be released while it is waiting
    synchronized(timer){
        timer.wait()
        //do whatever
    }
}

}

这将使“主”线程等到定时器线程调用notify方法,然后唤醒其中一个等待线程。

此外,我不认为“ActionListener”扩展了“TimerTask”。因此,代码示例可能无法编译,因为您向Timer提供了一个ActionListener,它希望TimerTask作为输入。或者也许我不知道你的代码应该做什么。

有关详细信息,请参阅How to use wait and notify in Java?