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

标签 java multithreading

我正在阅读 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/

相关文章:

java - 滚动 Pane 中的多种文本颜色?

java - 如何为多个整数创建 1 个 for 循环?

java - While 循环还是线程?

c - TCL 正则表达式是否跨解释器共享 - TclReExec 程序以信号 11,段错误终止?

c++ - 如何处理连接到 CPP 中服务器的多个客户端?

java - 如何使用 JMockit 模拟 void 方法异常

java - Android - 如何使用登录名和密码正确查询在线数据库?

java - Google App Engine (Java) + Spring 管理的 PersistenceManager

java - Java hashMap 中的线程安全

multithreading - 可以从另一个 QThread 安全地发出 Qt 信号吗