我尝试过延迟(或休眠)我的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.sleep(1000);                 //1000 milliseconds is one second.
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}
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);


  }
}

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

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

试试这个:

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