Ecco il frammento di codice:È necessario questo interrupt()?
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();
}
}
}
}
Come il codice di cui sopra, anche se mettiamo LoggerThread.interrupt() nel metodo stop(), l'interruzione solo essere catturato da filo e non fare nulla.
Quindi è LoggerThread.interrupt() necessario?
Eliminare la mia risposta come la tua è più accurata. –
Quindi 'InterruptedException' può essere passato a' queue.take() '? – user2916610
@ user2916610 l'eccezione non viene passata al metodo - il codice in 'queue.take()' controlla se il thread è interrotto su base regolare e genera un InterruptedException se il thread è interrotto. – assylias