我做了一个简单的功能来测试interrupt()
& Java中的InterruptedException
:
public static void main(String[] args) {
checkInterrupt();
}
private static void checkInterrupt() {
Runnable runMe = new Runnable() {
@Override
public void run() {
for(int i=0; i<6; i++) {
System.out.println("i = "+i);
if(i==3) {
System.out.println("i==3, Thread = "+Thread.currentThread().getId());
//I invoke interrupt() on the working thread.
Thread.currentThread().interrupt();
}
}
}
};
Thread workingThread = new Thread(runMe);
System.out.println("workingThread("+workingThread.getId()+") interrupted 1 ? "+workingThread.isInterrupted());
workingThread.start();
try {
workingThread.join();
} catch (InterruptedException e) {
//I thought I should get InterruptedException, but I didn't, why?
System.out.println("workingThread("+workingThread.getId()+") is interrupted.");
}
System.out.println("workingThread("+workingThread.getId()+") interrupted 2 ? "+workingThread.isInterrupted());
}
如上所述,在run()中,我在Thread.currentThread().interrupt()
时调用i==3
来中断工作线程。我认为我的代码应该在InterruptedException
期间抓住workingThread.join()
。但是根本没有例外。为什么呢?
答案 0 :(得分:2)
如果调用InterruptedException
的线程在等待另一个线程死亡时被中断,您将获得join
。这不是你的情况 - 你正在打断你正在加入的主题这是完全不同的事情。
答案 1 :(得分:0)
你正在打断错误的线程。来自Thread.join()
的文档:
InterruptedException - 如果有任何线程中断了当前线程。
您正在插入正在连接的线程,而不是正在进行连接的线程(在文档中称为当前线程)。
试试这个
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread() {
public void run() {
while (true) {}
}
};
t.start();
Thread.currentThread().interrupt();
t.join();
}
这是另一种变体,这次是从正在连接的线程中断。
public static void main(String[] args) throws InterruptedException {
final Thread mainThread = Thread.currentThread();
Thread t = new Thread() {
public void run() {
try {
Thread.sleep(10000);
mainThread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
t.join();
}