使用 Thread.sleep(x) 或 wait() 时出现异常 [英] I get exception when using Thread.sleep(x) or wait()

查看:25
本文介绍了使用 Thread.sleep(x) 或 wait() 时出现异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试延迟 - 或休眠 - 我的 Java 程序,但发生错误.

I have tried to delay - or put to sleep - my Java program, but an error occurs.

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

I'm unable to use Thread.sleep(x) or wait(). The same error message appears:

未报告的异常 java.lang.InterruptedException;必须被捕获或声明为抛出.

unreported exception java.lang.InterruptedException; must be caught or declared to be thrown.

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

Is there any step required before using the Thread.sleep() or wait() methods?

推荐答案

您需要阅读大量内容.从编译器错误到异常处理、线程和线程中断.但这会做你想做的:

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();
}

这篇关于使用 Thread.sleep(x) 或 wait() 时出现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆