简体   繁体   English

Java中使用线程的计时器

[英]timer in java using threads

I am developing an exam software in core java where I am conducting various tests for students.I am stuck at a piece of code where timer with countdown is set. 我正在用核心Java开发一个考试软件,在其中为学生进行各种测试。我被困在一段设置了倒数计时器的代码中。 My problem is when I display minutes its working fine but when I try to display seconds with the minutes in mm:ss format its not working. 我的问题是,当我显示分钟可以正常工作时,但是当我尝试以mm:ss格式显示分钟时却无法正常工作。

Code is: 代码是:

// for below int ti=20,si=60;
// test is for 20 minutes
public void run() {
    while (true) {
        try {
            Thread.currentThread().sleep(60000);

            for (int i = 0; i <= 60; i++) {
                etime.setText("Remaining Time:-" + ti + ":" + si);
                System.out.println("Remaining Time:-" + ti + ":" + si);
                Thread.currentThread().sleep(1000);
                si--;
            }
            ti--;
            if (ti == 0) {
                close();
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(Exam.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

Once si has counted down to 0, you need to reset it to 59. si倒数至0后,您需要将其重置为59。

Also, the i variable is completely unnecessary, and there is an off-by-one error in your loop. 另外, i变量完全没有必要,并且循环中存在一个错误的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM