我有一個關於中斷Java線程的問題。說我有一個Runnable
:Java - 中斷線程?
public MyRunnable implements Runnable {
public void run() {
operationOne();
operationTwo();
operationThree();
}
}
我想要實現這樣的事情:
Thread t = new Thread(new MyRunnable());
t.run();
... // something happens
// we now want to stop Thread t
t.interrupt(); // MyRunnable receives an InterruptedException, right?
... // t is has now been terminated.
我如何在Java中實現這一點?具體而言,我如何捕獲中的InterruptedException
?
順便說一句,如果你錯過了我的答案,第二行代碼應該是t.start(),而不是t.run()。 – user949300