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

Mis*_*eny 0 java timer execute

我正在制作一个非常简单的蛇游戏,我有一个名为Apple的对象,我想每隔X秒移动到一个随机位置.所以我的问题是,每X秒执行此代码的最简单方法是什么?

apple.x = rg.nextInt(470);
apple.y = rg.nextInt(470);
Run Code Online (Sandbox Code Playgroud)

谢谢.

编辑:

好吧有一个像这样的计时器:

Timer t = new Timer(10,this);
t.start();
Run Code Online (Sandbox Code Playgroud)

它的作用是在游戏启动时绘制我的图形元素,它运行以下代码:

@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);
Run Code Online (Sandbox Code Playgroud)

use*_*883 6

我会使用遗嘱执行人

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);
Run Code Online (Sandbox Code Playgroud)