嗨,我几个小时以来一直在尝试为我的 libgdx 游戏制作一个简单的 10 秒倒计时器,但我一直遇到问题。我现在在一个实现可运行的单独的类中运行倒计时器。这个类工作完美,它按计划倒计时,我在这个线程中运行了一个 system.out.println 来验证它的工作。问题是在我的主游戏屏幕中打印/绘制这个计时器变量。
如果我尝试从游戏屏幕打印这个变量,我会得到它的起始变量,即十,而不是不断更新的变量(从十开始倒数)。我什至使用了 getter 方法,但仍然没有运气。有什么想法如何实现这一目标?谢谢
我假设这是因为线程与主游戏并行运行?
public class timekeep implements Runnable {
public Boolean TimerRunning=true;
private int Timer = 10; //need to print this from my main game screen as it changes
public void run() {
while(TimerRunning == true) {
System.out.println("Time left "+ Timer);//works perfectly prints countdown
//run code
//subtracts 1 from Timer every second
}
}
public int gettime(){
return Timer;//returns timer
}
}
....
//accessing Timer variable from main game
System.out.println(Timekeep.gettime());//prints 10 all the time in the main screen
最佳答案
您的代码执行两个 new timekeep()
表达式,因此创建了两个对象。您需要重新编码,以便只创建一个 timekeep
对象。例如
timekeep theTimeKeeper = new timekeep() ;
Thread t1 = new Thread(theTimeKeeper));
t1.start() ;
...
System.out.println(theTimeKeeper.gettime());
关于java - 如何从我的线程倒计时类获取更新的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23186065/