在以下程序中,LoggerThread类中的this关键字是否引用LoggerThread对象或LogService对象?从逻辑上讲,它应该引用LogService以便进行同步,但是从语义上讲,它似乎是在引用LoggerThread。
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();
}
}
}
}
谢谢您的帮助
答案 0 :(得分:3)
this
方法中的 LoggerThread
引用一个LoggerThread
实例。
LogService.this
是指外部类。
isShutdown
和reservations
都通过不同的锁(LoggerThread.this
和LogService.this
)同步,因此@GuardedBy("this")
不能反映现实。
答案 1 :(得分:0)
这段代码来自《Java Concurrency In Practice》一书,代码清单 7.15
这是一个错字,在“勘误”部分中提到:
http://jcip.net.s3-website-us-east-1.amazonaws.com/errata.html
答案 2 :(得分:-1)