5
這裏的片段:這個中斷()是否必要?
public class LogService {
public void stop() {
synchronized (this) { isShutdown = true; }
loggerThread.interrupt(); /* Is it necesarry? */
}
public void log(String msg) throws InterruptedException {
synchronized (this) {
if (isShutdown)
throw new IllegalStateException(...);
++reservations;
}
queue.put(msg);
}
private class LoggerThread extends Thread {
public void run() {
try {
while (true) {
try {
synchronized (LogService.this) {
if (isShutdown && reservations == 0)
break;
}
String msg = queue.take();
synchronized (LogService.this) {
--reservations;
}
writer.println(msg);
} catch (InterruptedException e) { } /* Do nothing */
}
} finally {
writer.close();
}
}
}
}
正如上面的代碼,即使我們把LoggerThread.interrupt()在stop()方法,中斷只是被抓線程什麼都不做。
那麼LoggerThread.interrupt()是必要的嗎?
刪除我的答案是更準確的。 –
所以'InterruptedException'可以傳遞給'queue.take()'? – user2916610
@ user2916610該異常未傳遞給方法 - queue.take()中的代碼檢查線程是否定期中斷,並在線程中斷時拋出InterruptedException。 – assylias