在线程的情况下,Thread.sleep() 和 wait() 方法的异常处理有以下几点:
以下是一个示例代码:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadSleepWaitException {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
final int num = i;
executorService.submit(() -> {
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
// 处理异常,进行重试
if (num == 5) {
executorService.shutdown();
} else {
System.out.println("Thread " + num + " interrupted, retry...");
executorService.submit(() -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
});
}
}
});
}
executorService.shutdown();
}
}
在这个示例中,每个线程在休眠 2 秒后抛出 InterruptedException。当线程执行到 num == 5 时,会尝试重新启动线程,并在控制台输出 "Thread <num> interrupted, retry..."。如果重新启动失败,则会尝试稍后重试。
领取专属 10元无门槛券
手把手带您无忧上云