public class LogService {
private final BlockingQueue<String> queue;
private final LoggerThread loggerThread;
private final PrintWriter writer;
@GuardedBy("this") private boolean isShutdown;
@GuardedBy("this") private int reservations;
public void start() { loggerThread.start(); }
public void stop() {
synchronized (this) { isShutdown = true; }
loggerThread.interrupt();
}
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 (this) {
if (isShutdown && reservations == 0)
break;
}
String msg = queue.take();
synchronized (this) { --reservations; }
writer.println(msg);
} catch (InterruptedException e) { /* retry */ }
}
} finally {
writer.close();
}
}
}
}
这是“Java Concurrency In Practice”一书中的7.15。我无法理解同步在那里是如何工作的。为什么内部和外部类在访问字段的不同对象上同步? 这个错误和内部类必须使用synchronize(LogService.this)吗?或者我完全误解了同步是如何工作的?
答案 0 :(得分:3)
本书中出现错误,列于the errata
第154页:在代码清单7.15中,最后两行synchronized(this)行应该是同步读取的(LogService.this)。