gpt4 book ai didi

java - 需要示例程序来抛出 InterruptedException

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:41:46 25 4
gpt4 key购买 nike

我正在阅读 kathy sierra SCJP 1.5 第 9 章(线程),其中提到:

Notice that the sleep() method can throw a checked InterruptedException (you'll usually know if that is a possibility, since another thread has to explicitly do the interrupting), so you must acknowledge the exception with a handle or declare

我只需要一个示例程序来知道它何时发生(我可以在我的机器上运行)?

我用谷歌搜索但找不到任何示例代码来测试此功能..

提前致谢

最佳答案

这是一个例子:

public class Test
{
public static void main (String[] args)
{
final Thread mainThread = Thread.currentThread();

Thread interruptingThread = new Thread(new Runnable() {
@Override public void run() {
// Let the main thread start to sleep
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
mainThread.interrupt();
}
});

interruptingThread.start();

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("I was interrupted!");
}
}
}

遍历它:

  • 设置一个新的线程 hibernate 一段时间,然后中断主线程
  • 开始新线程
  • sleep 很长时间(在主线程中)
  • 当我们被中断时打印出一个诊断方法(同样,在主线程中)

主线程中的 sleep 不是严格必需的,但这意味着主线程在被中断之前确实开始 sleep 。

关于java - 需要示例程序来抛出 InterruptedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3642362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com