Javaスレッドを休止させるThread.sleep()関数の使い方

JavaのThread.sleep()メソッドは、現在の実行中のスレッドを一時停止するために使用されます。使用方法は 2 つあります。

  1. 一定時間間隔を使用する:
try {
    // 暂停执行500毫秒(0.5秒)
    Thread.sleep(500);
} catch (InterruptedException e) {
    e.printStackTrace();
}
  1. 動的タイムスライディング
try {
    // 暂停执行一段时间,时间间隔为动态变量milliseconds
    long milliseconds = 1000;
    Thread.sleep(milliseconds);
} catch (InterruptedException e) {
    e.printStackTrace();
}

スレッドがスリープ中に割り込みがあった場合に発生するInterruptedException例外に対応するために、Thread.sleep()を呼び出す場合は通常、try〜catchブロック内で処理する必要があります。

bannerAds