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。我不明白同步在那里如何工作。为什么内部类和外部类在访问字段的不同对象上同步?
是这个错误,内部类必须使用sync(LogService.this)吗?还是我完全误解了同步的工作原理?

最佳答案

这是书中的错误,列在the errata

p.154:在代码清单7.15中,最后两行同步(this)行应显示为已同步(LogService.this)。

10-01 14:20
查看更多