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

在Java中,如何每X秒执行一次代码?,java,timer,execute,Java,Timer,Execute,我正在做一个非常简单的蛇游戏,我有一个叫做苹果的物体,我想每X秒移动到一个随机的位置。所以我的问题是,每X秒执行一次代码最简单的方法是什么 apple.x = rg.nextInt(470); apple.y = rg.nextInt(470); 谢谢 编辑: 我们已经有了这样的计时器: Timer t = new Timer(10,this); t.start(); 它所做的是在游戏开始时绘制我的图形元素,它运行以下代码: @Override public void actionP

我正在做一个非常简单的蛇游戏,我有一个叫做苹果的物体,我想每X秒移动到一个随机的位置。所以我的问题是,每X秒执行一次代码最简单的方法是什么

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

编辑:

我们已经有了这样的计时器:

Timer t = new Timer(10,this);
t.start();
它所做的是在游戏开始时绘制我的图形元素,它运行以下代码:

@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);

最简单的方法是使用
睡眠

        apple.x = rg.nextInt(470);
        apple.y = rg.nextInt(470);
        Thread.sleep(1000);
在循环中运行上述代码


这将给您一个近似的(可能不准确)1秒延迟。

您应该有某种游戏循环,负责处理游戏。您可以每隔x毫秒触发此循环中要执行的代码,如下所示:

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

        lastExecution = System.currentTimeMillis();
    }
}

在本例中,if语句中的条件将每隔1000毫秒计算一次
true

我将使用执行器

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);
ScheduledExecutorService调度器=执行者。newScheduledThreadPool(1);
Runnable toRun=新的Runnable(){
公开募捐{
System.out.println(“您的代码…”);
}
};
ScheduledFuture handle=scheduler.scheduleAtFixedRate(toRun,1,1,TimeUnit.SECONDS);
使用计时器:

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);

文档:

可能重复我有一个计时器,我编辑了我的问题,这样你可以看到它是什么样子。你的蛇游戏有线程吗?不,我不知道线程是什么,哈哈^_^