多线程如何在对Java线程使用join()时导致InterruptedExpection? 1 周 Questions & Answers 48 我正在编写一个测试用例,需要在调用join()的try-catch块中抛出InterruptedExpection。有什么例子吗
# 1 楼答案 当然。只需从另一个线程调用theThreadThatJoined.interrupt() public class JoinInterruptedExceptionExample { public static void main(String[] args) { final Thread workerThread = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } } }); workerThread.start(); final Thread waitingThread = new Thread(new Runnable() { @Override public void run() { try { workerThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }); waitingThread.start(); waitingThread.interrupt(); } }
# 1 楼答案
当然。只需从另一个线程调用
theThreadThatJoined.interrupt()