从主线程休眠是抛出InterruptedException

Chr*_*ris 9 java multithreading

我有执行的主线程产生新线程.在main()执行的主线程中,我正在调用Thread.sleep().我什么时候得到未处理的异常类型InterruptedException

我不确定为什么我会这样做.我认为这是因为我需要一个对主线程的引用所以我继续前进并通过它引用它Thread.currentThread().

这不是让线程睡觉的方法吗?我需要做的是让主线程等待/睡眠/延迟,直到它再次需要工作.

Eya*_*der 20

您看到的是编译错误,因为您没有正确处理已检查的异常(InterruptedException在本例中).处理意味着执行以下操作之一:

1)将方法声明为throws InterruptedException,因此要求调用者处理异常

2)用try{..}catch(..){..}块抓住它.例如:

try {
    Thread.sleep(1500);
} catch(InterruptedException e) {
    System.out.println("got interrupted!");
}
Run Code Online (Sandbox Code Playgroud)

InterruptedException 用于指示当前线程在执行某些阻塞操作时被外部线程中断(例如,可中断IO,等待,休眠)