在线程等待后,计时器继续运行

时间:2015-04-03 22:06:18

标签: java multithreading

这里发生了什么?每当我按下开始按钮时,它就会在我的JLabel上从00:00:000开始计数(很好,这就是我想要的)。按下停止按钮后说00:10:000,我看到我的JLabel在00:10:000(很好,这就是我想要的)。好的,这就是问题所在,每当我再次按下开始按钮时,我希望它从00:10:000开始。但事实并非如此,因为计数器一直在后台运行。所以说我的JLabel站在00:10:000并且正好等待00:07:000并再次按下开始按钮,它再次从00:17:000开始计数。那么任何人都可以帮助我吗?提前谢谢!

private boolean isRunning;
private boolean isWaiting;

public void run()
{
    long calibration1 = System.currentTimeMillis();

    try
    {
        while(isRunning == true) //start button
        {
            long yourmilliseconds1 = System.currentTimeMillis();
            SimpleDateFormat sdf1 = new SimpleDateFormat("mm:ss:SSS");

            System.out.println(sdf1.format(yourmilliseconds1 - calibration1));
            String outputTimer = sdf1.format(yourmilliseconds1 - calibration1);

            timerLabel.setText(outputTimer);

            if(isWaiting == true) // stop button        
            {
                synchronized(this)
                {
                    wait(); //if start button is pressed again it will notify() (no need for code)                  }
            }
        }
    }

    catch(InterruptedException e)
    {

    }   
}

public void startButton()
{
    isWaiting = false;
    isRunning = true;
}

public void stopButton()
{
    isWaiting = true;
    isRunning = false;
}

0 个答案:

没有答案