我尝试过延迟(或休眠)我的Java程序,但是出现了一个错误。

我无法使用Thread.sleep(x)或wait()。同样的错误信息出现:

interruptedexception;必须被捕获或宣布被丢弃。

在使用Thread.sleep()或wait()方法之前,是否需要任何步骤?


当前回答

放置你的线程。睡在一个尝试捕捉块

try {
    //thread to sleep for the specified number of milliseconds
    Thread.sleep(100);
} catch ( java.lang.InterruptedException ie) {
    System.out.println(ie);
}

其他回答

或者,如果你不想处理线程,试试这个方法:

public static void pause(int seconds){
    Date start = new Date();
    Date end = new Date();
    while(end.getTime() - start.getTime() < seconds * 1000){
        end = new Date();
    }
}

它在您调用它时开始,在秒数过去时结束。

当使用Android(我唯一一次使用Java)时,我会建议使用处理程序而不是让线程进入睡眠状态。

final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Log.i(TAG, "I've waited for two hole seconds to show this!");

        }
    }, 2000);

参考:http://developer.android.com/reference/android/os/Handler.html

使用java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

睡一秒钟或者

TimeUnit.MINUTES.sleep(1);

睡一分钟。

由于这是一个循环,这就提出了一个固有的问题-漂移。每次你运行代码然后睡觉的时候,你都会从运行中飘忽不定,比如说,每一秒。如果这是一个问题,那么不要使用睡眠。

此外,当涉及到控制时,睡眠不是很灵活。

对于每秒钟运行一个任务或在一秒延迟,我强烈建议[ScheduledExecutorService][1]和[scheduleAtFixedRate][2]或[scheduleWithFixedDelay][3]。

每秒运行myTask方法(Java 8):

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

试试这个:

try{

    Thread.sleep(100);
}catch(Exception e)
{
   System.out.println("Exception caught");
}

放置你的线程。睡在一个尝试捕捉块

try {
    //thread to sleep for the specified number of milliseconds
    Thread.sleep(100);
} catch ( java.lang.InterruptedException ie) {
    System.out.println(ie);
}