【发布时间】:2016-10-02 07:58:08
【问题描述】:
我正在尝试用 Java 编写我的第一个多线程程序。我不明白为什么我们需要围绕 for 循环进行这种异常处理。当我在没有 try/catch 子句的情况下编译时,它会给出一个InterruptedException。
这是消息:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type InterruptedException
但是当使用 try/catch 运行时,catch 块中的 sysout 永远不会显示 - 这意味着无论如何都没有捕获到此类异常!
public class SecondThread implements Runnable {
Thread t;
SecondThread() {
t = new Thread(this, "Thread 2");
t.start();
}
public void run() {
try {
for (int i=5; i>0; i--) {
System.out.println("thread 2: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("thread 2 interrupted");
}
}
}
public class MainThread {
public static void main(String[] args) {
new SecondThread();
try {
for (int i=5; i>0; i--) {
System.out.println("main thread: " + i);
Thread.sleep(2000);
}
}
catch (InterruptedException e) {
System.out.println("main thread interrupted");
}
}
}
【问题讨论】:
-
When I compile without the try/catch clauses it gives an InterruptedException: 不,它没有,它给出了一个错误,你没有捕捉到检查的异常——这与编译器给你一个异常是非常不同的。 -
当我编译时,它说:线程“main”java.lang.Error中的异常:未解决的编译问题:未处理的异常类型InterruptedException at MainThread.main(MainThread.java:10)
-
@SergioGliesh:edit你的问题,不要写在评论里。
-
如果你不想处理
InterruptedException,一种选择是使用Guava的Uninterruptibles.sleepUninterruptibly(),它可以适当地抑制InterruptedException,但是(顾名思义)意味着你不能更长的时间打断睡眠,这通常不是你真正想做的。
标签: java interrupted-exception interruption