更新可运行类中的变量值

  • 本文关键字:变量值 运行 更新 java
  • 更新时间 :
  • 英文 :


我是java的初学者。从Main类更新TimerRunable类中的变量时遇到问题。这样做可能吗?

这是我的Main.java

class Main {
public static void main(String[] args) {
TimerRunnable tr = new TimerRunnable(5);
Thread thread = new Thread(tr);
thread.start();
try {
Thread.sleep(2000L);
} catch(Exception ignored) {}
System.out.println("main");
tr.resetTimer(true);
}
}

TimerRunable.java:

import java.lang.Thread;
public class TimerRunnable implements Runnable {
public boolean reset = false;
private int sec;
public TimerRunnable(int sec) {
this.sec = sec;
}
public synchronized void resetTimer(boolean v) {
this.reset = v;
}
private synchronized boolean checkResetTimer() {
return this.reset;
}
@Override
public void run() {
int i = this.sec;
while(i>=0) {
if(this.checkResetTimer()) {
i=sec;
System.out.println(i);
}
System.out.println(Thread.currentThread().getName() + " = " + i + "/" + sec);
try {
Thread.currentThread().sleep(1000L);
} catch(Exception e) {}
if(this.checkResetTimer()) {
resetTimer(false);
}
i--;
}
}
}

输出:

[me@laptop java]$ java Main
Thread-0 = 5/5
Thread-0 = 4/5
main
Thread-0 = 3/5
Thread-0 = 2/5
Thread-0 = 1/5
Thread-0 = 0/5

预期输出:

[me@laptop java]$ java Main
Thread-0 = 5/5
Thread-0 = 4/5
main
Thread-0 = 5/5
Thread-0 = 4/5
Thread-0 = 3/5
Thread-0 = 2/5
Thread-0 = 1/5
Thread-0 = 0/5

我在TimerRunable类中更新变量的目标是使倒计时计时器可以返回到其原始值。

问题是,你在跑步者睡觉时进行重置,然后它总是清除重置并继续。要修复此问题,请首先更新跑步者中的第一次重置检查

if(this.checkResetTimer()) {
i=sec;
System.out.println(i);
resetTimer(false);
}

然后去掉第二次检查

// if(this.checkResetTimer()) {
//     resetTimer(false);
// }

最新更新