我正在尝试从此类外部调用“ Timer”类的“ checkTime”方法,但这种方法不起作用...这是正确的方法吗?我怎样才能解决这个问题?我正在使用线程
class Timer implements Runnable{
private boolean running;
private int time = 0;
public Timer(){
time = 10;
running = false;
}
public boolean isRunning(){
return running;
}
public void checkTime(){
if(isRunning()){
System.out.println("Timer is at: "+ time/1000 + " seconds");
}
}
@Override
public void run() {
try {
running = true;
Thread.sleep(1000L);
}
running = false;
}
}
}
在另一个班上,我有这样的事情
Thread timer;
timer = new Thread(new Timer());
//check timer
if(cooking){
timer.checkTime();
} else{
System.out.println("The timer is set to: " + timer + " seconds");
}
break;```
答案 0 :(得分:1)
在实例化Thread对象之前,请为Timer对象提供一个变量。
示例:
Timer timer = new Timer();
Thread thread = new Thread(timer);
// get the checkTime() value here
System.out.println(timer.checkTime());
您真的需要提防并发问题,因为您有多个线程管理相同的变量(int time
和boolean running
)。