如何延迟一个方法

1 java netbeans

我正在做一个othello游戏,我做了一个简单的代码.但是当我运行我的代码时,Ai在我点击之后就运行了,我想要一些延迟,我真的不知道怎么做,正如我所说,它跑得快,我希望艾未未如此运行2秒.

board.artificialIntelligence();
Run Code Online (Sandbox Code Playgroud)

我的方法Ai存储在板类中,我希望它在我的面板类中,顺便说一句,我正在使用NetBeans.

Cae*_*alf 5

如果您这样做,Thread.sleep(TIME_IN_MILLIS)您的游戏将在2秒内无响应(除非此代码在另一个线程中运行).

我能看到的最好的方法是ScheduledExecutorService在你的班级中有一个并将AI任务提交给它.就像是:

public class AI {

    private final ScheduledExecutorService execService;

    public AI() {
        this.execService = Executors.newSingleThreadScheduledExecutor();
    }

    public void startBackgroundIntelligence() {
        this.execService.schedule(new Runnable() {
            @Override
            public void run() {
                // YOUR AI CODE
            }
        }, 2, TimeUnit.SECONDS);
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.干杯.