在下面的程序中,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(); } } }}感谢您的帮助
3 回答
![?](http://img1.sycdn.imooc.com/54584c5e0001491102200220-100-100.jpg)
慕娘9325324
TA贡献1783条经验 获得超4个赞
this
LoggerThread
方法内是指一个LoggerThread
实例。LogService.this
指的是外部类。
二者isShutdown
并reservations
通过不同的锁(同步LoggerThread.this
和LogService.this
),因此@GuardedBy("this")
不反映现实。
![?](http://img1.sycdn.imooc.com/545850ee0001798a02200220-100-100.jpg)
紫衣仙女
TA贡献1839条经验 获得超15个赞
this
指的是直接封闭类的当前实例。JLS #15.8.4 .
从逻辑上讲,它应该引用 LogService 以便同步工作,但从语义上讲,它似乎指的是 LoggerThread。
正确的。这是一个错误。
添加回答
举报
0/150
提交
取消