简体   繁体   English

在Java中,如何每隔X秒执行一次代码?

[英]In Java, how do I execute code every X seconds?

I'm making a really simple snake game, and I have an object called Apple which I want to move to a random position every X seconds. 我正在做一个非常简单的蛇游戏,并且有一个名为Apple的对象,我希望每X秒移动到一个随机位置。 So my question is, what is the easiest way to execute this code every X seconds? 所以我的问题是,每X秒执行此代码的最简单方法是什么?

apple.x = rg.nextInt(470);
apple.y = rg.nextInt(470);

Thanks. 谢谢。

Edit: 编辑:

Well do have a timer already like this: 好吧,已经有一个这样的计时器了:

Timer t = new Timer(10,this);
t.start();

What it does is draw my graphic elements when the game is started, it runs this code: 它的作用是在游戏启动时绘制我的图形元素,它运行以下代码:

@Override
    public void actionPerformed(ActionEvent arg0) {
        Graphics g = this.getGraphics();
        Graphics e = this.getGraphics();
        g.setColor(Color.black);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        e.fillRect(0, 0, this.getWidth(), this.getHeight());
        ep.drawApple(e);
        se.drawMe(g);

I would use an executor 我会用遗嘱执行人

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    Runnable toRun = new Runnable() {
        public void run() {
            System.out.println("your code...");
        }
    };
ScheduledFuture<?> handle = scheduler.scheduleAtFixedRate(toRun, 1, 1, TimeUnit.SECONDS);

Simplest thing is to use sleep . 最简单的事情就是利用sleep

        apple.x = rg.nextInt(470);
        apple.y = rg.nextInt(470);
        Thread.sleep(1000);

Run the above code in loop. 循环运行以上代码。

This will give you an approximate (may not be exact) one second delay. 这将使您大约延迟一秒钟(可能不准确)。

You should have some sort of game loop which is responsible for processing the game. 您应该具有某种负责处理游戏的游戏循环。 You can trigger code to be executed within this loop every x milliseconds like so: 您可以每隔x毫秒触发一次在此循环内执行的代码,如下所示:

while(gameLoopRunning) {
    if((System.currentTimeMillis() - lastExecution) >= 1000) {
        // Code to move apple goes here.

        lastExecution = System.currentTimeMillis();
    }
}

In this example, the condition in the if statement would evaluate to true every 1000 milliseconds. 在此示例中,if语句中的条件每1000毫秒评估为true

Use a timer: 使用计时器:

Timer timer = new Timer();
int begin = 1000; //timer starts after 1 second.
int timeinterval = 10 * 1000; //timer executes every 10 seconds.
timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
    //This code is executed at every interval defined by timeinterval (eg 10 seconds) 
   //And starts after x milliseconds defined by begin.
  }
},begin, timeinterval);

Documentation: Oracle documentation Timer 文档: Oracle文档计时器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM