Java 使用 Thread.sleep(x) 或 wait() 时出现异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3342651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I get exception when using Thread.sleep(x) or wait()
提问by vincent low
I have tried to delay - or put to sleep - my Java program, but an error occurs.
我曾尝试延迟 - 或休眠 - 我的 Java 程序,但发生错误。
I'm unable to use Thread.sleep(x)
or wait()
. The same error message appears:
我无法使用Thread.sleep(x)
或wait()
。出现相同的错误消息:
unreported exception java.lang.InterruptedException; must be caught or declared to be thrown.
未报告的异常 java.lang.InterruptedException; 必须被捕获或声明被抛出。
Is there any step required before using the Thread.sleep()
or wait()
methods?
在使用Thread.sleep()
或wait()
方法之前是否需要任何步骤?
采纳答案by Konrad Garus
You have a lot of reading ahead of you. From compiler errors through exception handling, threading and thread interruptions. But this will do what you want:
你有很多阅读要做。从编译器错误到异常处理、线程和线程中断。但这会做你想做的:
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
回答by Abel
Have a look at this excellent brief poston how to do this properly.
Essentially: catch the InterruptedException
. Remember that you must add this catch-block. The post explains this a bit further.
本质上:抓住InterruptedException
. 请记住,您必须添加此捕获块。这篇文章进一步解释了这一点。
回答by Jatin
Use the following coding construct to handle exceptions
使用以下编码结构来处理异常
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
//Handle exception
}
回答by JoseK
Put your Thread.sleep
in a try catch block
把你的Thread.sleep
放在一个 try catch 块中
try {
//thread to sleep for the specified number of milliseconds
Thread.sleep(100);
} catch ( java.lang.InterruptedException ie) {
System.out.println(ie);
}
回答by SlickJava
Try this:
尝试这个:
try{
Thread.sleep(100);
}catch(Exception e)
{
System.out.println("Exception caught");
}
回答by user2276378
Alternatively, if you don't want to deal with threads, try this method:
或者,如果您不想处理线程,请尝试以下方法:
public static void pause(int seconds){
Date start = new Date();
Date end = new Date();
while(end.getTime() - start.getTime() < seconds * 1000){
end = new Date();
}
}
It starts when you call it, and ends when the number of seconds have passed.
它在您调用它时开始,并在经过秒数时结束。
回答by Alexander Ivanov
As other users have said you should surround your call with a try{...} catch{...}
block. But since Java 1.5 was released, there is TimeUnit class which do the same as Thread.sleep(millis)but is more convenient.
You can pick time unit for sleep operation.
正如其他用户所说,您应该用一个try{...} catch{...}
块来包围您的呼叫。但是自从 Java 1.5 发布后,就有了 TimeUnit 类,它的作用与Thread.sleep(millis)相同,但更方便。您可以选择睡眠操作的时间单位。
try {
TimeUnit.NANOSECONDS.sleep(100);
TimeUnit.MICROSECONDS.sleep(100);
TimeUnit.MILLISECONDS.sleep(100);
TimeUnit.SECONDS.sleep(100);
TimeUnit.MINUTES.sleep(100);
TimeUnit.HOURS.sleep(100);
TimeUnit.DAYS.sleep(100);
} catch (InterruptedException e) {
//Handle exception
}
Also it has additional methods: TimeUnit Oracle Documentation
它还有其他方法: TimeUnit Oracle 文档
回答by Alexander Ivanov
public static void main(String[] args) throws InterruptedException {
//type code
short z=1000;
Thread.sleep(z);/*will provide 1 second delay. alter data type of z or value of z for longer delays required */
//type code
}
eg:-
例如:-
class TypeCasting {
public static void main(String[] args) throws InterruptedException {
short f = 1;
int a = 123687889;
short b = 2;
long c = 4567;
long d=45;
short z=1000;
System.out.println("Value of a,b and c are\n" + a + "\n" + b + "\n" + c + "respectively");
c = a;
b = (short) c;
System.out.println("Typecasting...........");
Thread.sleep(z);
System.out.println("Value of B after Typecasting" + b);
System.out.println("Value of A is" + a);
}
}
回答by D.R.Bendanillo
My ways to add delay to a Java program.
我为 Java 程序添加延迟的方法。
public void pause1(long sleeptime) {
try {
Thread.sleep(sleeptime);
} catch (InterruptedException ex) {
//ToCatchOrNot
}
}
public void pause2(long sleeptime) {
Object obj = new Object();
if (sleeptime > 0) {
synchronized (obj) {
try {
obj.wait(sleeptime);
} catch (InterruptedException ex) {
//ToCatchOrNot
}
}
}
}
public void pause3(long sleeptime) {
expectedtime = System.currentTimeMillis() + sleeptime;
while (System.currentTimeMillis() < expectedtime) {
//Empty Loop
}
}
This is for sequential delay but for Loop delays refer to Java Delay/Wait.
这是针对顺序延迟,但对于循环延迟,请参阅Java Delay/Wait。
回答by Sindri Tór
When using Android(the only time when I use Java) I would recommend using a handler instead putting the thread to sleep.
使用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);
Reference: http://developer.android.com/reference/android/os/Handler.html
参考:http: //developer.android.com/reference/android/os/Handler.html