我尝试过延迟(或休眠)我的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);
}

其他回答

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

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

看看这篇关于如何正确做到这一点的简短文章。

本质上:捕获InterruptedException。记住,您必须添加这个捕获块。这篇文章对此作了进一步的解释。

一种更简单的等待方法是使用System.currentTimeMillis(),它返回自UTC 1970年1月1日午夜以来的毫秒数。例如,等待5秒:

public static void main(String[] args) {
    //some code
    long original = System.currentTimeMillis();
    while (true) {
        if (System.currentTimeMillis - original >= 5000) {
            break;
        }
    }
    //more code after waiting
}

这样,您就不必处理线程和异常。 希望这能有所帮助!

使用下面的编码结构来处理异常

try {
  Thread.sleep(1000);
} catch (InterruptedException ie) {
    //Handle exception
}

当使用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