Java-由计时器控制的多个对象(用于游戏)

Java-由计时器控制的多个对象(用于游戏),java,android,multithreading,timer,Java,Android,Multithreading,Timer,我目前正在开发一个小游戏,它由几个目标组成,这些目标在不同的时间段内随机弹出。因为目标是物理的,所以实际的游戏将从电路板获得它的I/O 我的问题是,目前我有一个java.util.Timer,它每2秒就会触发一次。一旦触发,将显示一个随机目标(目前为止效果良好)。问题是,我想在计时器仍在运行和设置其他目标时,在1-5之间随机显示目标秒数 我没有收到错误,目标显示,但从未消失。我猜这是某种线程问题,可能是因为我使用了这个。*目标对象只是不知何故在虚空中迷失了方向!在搜索了这里的问题后,我得出了以下

我目前正在开发一个小游戏,它由几个目标组成,这些目标在不同的时间段内随机弹出。因为目标是物理的,所以实际的游戏将从电路板获得它的I/O

我的问题是,目前我有一个java.util.Timer,它每2秒就会触发一次。一旦触发,将显示一个随机目标(目前为止效果良好)。问题是,我想在计时器仍在运行和设置其他目标时,在1-5之间随机显示目标秒数

我没有收到错误,目标显示,但从未消失。我猜这是某种线程问题,可能是因为我使用了这个。*目标对象只是不知何故在虚空中迷失了方向!在搜索了这里的问题后,我得出了以下结论:

public class Target implements Runnable(){

  ...

    public void displayFor(int seconds){
        this.display();

        Executors.newSingleThreadScheduledExecutor().schedule(this,time,
                TimeUnit.SECONDS);

        this.setDisplayed(false);
    }

    @Override
    public void run() {
        this.destroy();
    }

}
基本上,初始游戏计时器(设置目标显示)调用displayFor(2)方法,该方法在时间过后运行目标运行方法。但目标仍然不会消失

我尝试了很多不同的方法,比如displayFor()设置另一个java.util.Timer,我还尝试过使用Quartz库(老实说,这似乎有些过火),但仍然无法让它工作。因为没有错误消息,我真的被这条消息困住了


我没有包含太多的代码,因为我认为它没有那么重要,但如果你们需要更多信息来帮助,请告诉我:)

也许你们应该告诉我们
显示方法的作用

您是否un-在
destroy
/destrouctor代码中显示目标

我建议用代替
void display()

当然

public void run(){
  setDisplayed(false);
  destroy();
}

我设法使它工作起来。下面是适用于任何处于类似情况的人的正确代码

public class Target{

private Timer timer;

   ...

   public void displayFor(int seconds) {
     // send the output
     BoardInterface.SetDigitalChannel(this.getId());

     // calculate the delay
     long time = seconds * 1000;

     // create a new timer and schedule the new task
     timer = new Timer();
     timer.schedule(new TargetTimer(this), time);

     this.setDisplayed(true);
  }
}

class TargetTimer extends TimerTask{
   Target target;

   public TargetTimer(Target t){
       this.target = t;
   }

   @Override
   public void run() {
       target.destroy();
   }

}

不确定这是否是一个好的方法,但它的工作。如果您注意到任何可以改进的地方,请告诉我。谢谢大家

当你画它们的时候,你每次都在清理画布吗?或者你只是在它们出现时绘制它们。@glowcoder我没有绘制任何东西,目标是真实世界中的物理对象,所以当我显示时,我将输出发送到电路板。你不应该在每次displayFor()调用上创建新的执行者。让它成为班级成员并重新使用。事实上,我刚刚发现了它,并让它发挥作用,但由于我的声望,我在接下来的6个小时内无法回答我自己的问题。实际上我也创建了你所说的setDisplay()方法!谢谢你的帮助,也谢谢大家。我会尽可能用我的答案回答这个问题。
public class Target{

private Timer timer;

   ...

   public void displayFor(int seconds) {
     // send the output
     BoardInterface.SetDigitalChannel(this.getId());

     // calculate the delay
     long time = seconds * 1000;

     // create a new timer and schedule the new task
     timer = new Timer();
     timer.schedule(new TargetTimer(this), time);

     this.setDisplayed(true);
  }
}

class TargetTimer extends TimerTask{
   Target target;

   public TargetTimer(Target t){
       this.target = t;
   }

   @Override
   public void run() {
       target.destroy();
   }

}