暂停带有睡眠线程的秒表计时器吗?

问题描述 投票:0回答:1

我正在尝试用Java制作秒表,但不知道如何暂停和继续计时器。这是我到目前为止所做的。

startButton.addActionListener(this);
stopButton.addActionListener(this);
pauseButton.addActionListener(this);

public void actionPerformed(ActionEvent e) {
    Calendar aCalendar = Calendar.getInstance();
    if (e.getSource() == startButton){
        start = aCalendar.getTimeInMillis();
        startButton.setBackground(Color.GREEN);
        stopButton.setBackground(null);
        pauseButton.setBackground(null);
    } else if (e.getSource() == stopButton) {
        stopButton.setBackground(Color.RED);
        startButton.setBackground(null);
        pauseButton.setBackground(null);
        aJLabel.setText("Elapsed time is: " + 
                (double) (aCalendar.getTimeInMillis() - start) / 1000 );
    } else if (e.getSource() == pauseButton) {
        pauseButton.setBackground(Color.YELLOW);
        stopButton.setBackground(null);
        startButton.setBackground(null);
    }
}

如您所见,我只更改了暂停按钮的颜色。我真的不知道如何通过让用户单击按钮来暂停线程。我发现的thread.sleep()的所有示例都具有特定的时间。

java timer thread-sleep
1个回答
0
投票

您可以像这样使用swing.Timer(而不是util.Timer):

int interval = 100; // set milliseconds for each loop
Timer timer = new Timer(interval, (evt) -> repeatingProccess());
// create the method  repeatingProccess() with your
// code that makes the clock tick


startButton.addActionListener(e -> timer.start());
stopButton.addActionListener( e -> {
    timer.stop(); 
    // here refresh your clock with some code... 
};
pauseButton.addActionListener(e -> timer.stop());

您编写了一个名为repeatingProccess()的方法,它每隔interval毫秒一次又一次地在其自己的线程中工作。对于数秒的时钟,您可以执行以下操作:

int interval = 1000;
int seconds = 0;
public void repeatingProccess() {
    seconds++ ;
}

注意:由于运行seconds++所需的时间,秒数不是精确的1000毫秒,而是1001左右,但是您也可以通过获取前后的系统时间并减去时钟差来解决此问题。您应该为此使用Calendar API。

© www.soinside.com 2019 - 2024. All rights reserved.