私は、オセロ ゲームをやっていて、簡単なコードである Ai をしました。しかし、コードを実行すると、クリックした直後に Ai が実行されます。遅延が必要です。どうすればよいかわかりません。前述のように、実行速度が速く、Ai を次のように実行したい2秒。
board.artificialIntelligence();
私のメソッド Ai はボード クラスに保存されており、それをパネル クラスに入れたいのですが、NetBeans を使用しています。
これを行うと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);
    }
}
お役に立てれば。乾杯。
Swing を使用している場合は、Swing タイマーを使用して、定義済みの遅延の後にメソッドを呼び出すことができます。
Timer timer = new Timer(2000, new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
         board.artificialIntelligence();
      }
   });
timer.setRepeats(false);
timer.start();
    int numberOfMillisecondsInTheFuture = 2000;
    Date timeToRun = new Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture);
    timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {
                     board.artificialIntelligence();
        }
    }, timeToRun);
    メイン スレッドをブロックしたくない場合は、次のように、2 秒待機してから呼び出しを行う (その後終了する) 新しいスレッドを開始します。
new Thread(new Runnable() {
    public void run() {
        try {
            Thread.sleep(2000);
        } (catch InterruptedException e) {}
        board.artificialIntelligence();
    }
}).start();
    を使用Thread.sleep(2000)して 2 秒間待ちます
Thread.sleep は、指定された期間、現在のスレッドの実行を中断させます。
あなたの場合:
Thread.sleep(2000); // will wait for 2 seconds
    コード呼び出しの前に
try {    
    Thread.sleep(2000);
} catch(InterruptedException e) {}
    次のコードを使用して 2 秒間待ちます。
long t0,t1;
t0=System.currentTimeMillis();
do{
   t1=System.currentTimeMillis();
}while (t1-t0<2000);