有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java AtomicInteger似乎不适合我

我正在尝试为我的Libgdx游戏创建一个简单的10秒倒计时计时器。我已经创建了一个timekeep类,它实现了runnable,并且可以很好地进行10秒倒计时。然而,我想打印这个Timer变量,因为它在我的主游戏杯中发生了变化,但由于某些原因,我无法这样做。我一直收到一个空指针异常。我想这可能是一个同步错误,因为Render在它自己的线程中运行,而我的timekeep运行它自己的线程。我尝试过volatile变量和同步gettime方法,现在尝试了原子整数,但没有成功。如何从我的timekeep类获取Timer变量,并在更新时从我的主游戏类打印它?谢谢

这是我的计时课

public class timekeep implements Runnable {
    public volatile Boolean TimerRunning = true;
    //private int Timer = 10;//I want to print this variable as it counts down
    public AtomicInteger Timer = new AtomicInteger(10);
    public int Timeleft;


    @Override

    public void run() {

        while (TimerRunning == true) {
            System.out.println("Time left" + Timer);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (Timer.equals(0)) {

                TimerRunning = false;

            } else {

                Timer.decrementAndGet();

            }

        }

    }

    public int getTimer() {
        return Timer.get();   
    }

}

其他主要游戏屏幕类 计时

 //constructor
 Timekeep = new timekeep();
 //on show create the thread
 timekeep Timekeep = new timekeep();//inside show method in main game screen class
 Thread t1 = new Thread(Timekeep);
 t1.start();
 //inside the render method 
 System.out.println(Timekeep.getTimer());//inside render method in main game screenclass

共 (1) 个答案

  1. # 1 楼答案

    改变现状

    if(Timer.equals(0))
    

    if (getTimer() == 0)
    

    AtomicInteger不重写equals方法。传递的是原语int 0,它将不等于对象AtomicInteger。获取int值并与0进行比较