如何在Java中暂停/恢复和停止我的计时器?

时间:2016-09-12 13:53:37

标签: java multithreading

我已经有了开始按钮的代码 - 已经引用了JLabel。但是我在编写暂停/恢复和停止时遇到了麻烦。我还搜索了“计划”功能,但我不知道如何实现它。请帮忙。

  /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package com.pingol.thread;

    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JLabel;


    public class Timer implements Runnable {

        JLabel miliseconds;
        JLabel seconds;
        JLabel minute;

        public Timer(JLabel miliseconds, JLabel seconds, JLabel minute){
            this.miliseconds = miliseconds;
            this.seconds = seconds;
            this.minute = minute;
        }
        @Override
        public void run() {
            for (int i = 0; i < 60; i++){ 
                this.minute.setText(Integer.toString(i));
                for (int j = 0; j < 60; j++) {
                      this.seconds.setText(Integer.toString(j));
                    for (int k = 0; k < 60; k++) {
                        this.miliseconds.setText(Integer.toString(k));
                          try {
                              Thread.sleep(10);
                          } catch (InterruptedException ex) {
                              Logger.getLogger(Timer.class.getName()).log(Level.SEVERE, null, ex);
                          }
                    }
                }
            }
        } 
    }
/*
FRAME (s**strong text**tart):

private void startActionPerformed(java.awt.event.ActionEvent evt) {                                      
        Timer timer = new Timer(miliseconds,seconds,minutes);
        Thread th = new Thread(timer);
        th.start();
    }  
*/

1 个答案:

答案 0 :(得分:0)

使您的线程变量成为类变量。然后在你的startActioPerformed中调用th.start()。在pauseActionPerformed中调用th.wait(); 并在您的resumeActionPerform中调用th.resume();