在下面的程序中,LoggerThread類中的this關(guān)鍵字是指LoggerThread對象還是LogService對象?從邏輯上講,它應(yīng)該引用 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 回答

慕娘9325324
TA貢獻1783條經(jīng)驗 獲得超4個贊
this
LoggerThread
方法內(nèi)是指一個LoggerThread
實例。LogService.this
指的是外部類。
二者isShutdown
并reservations
通過不同的鎖(同步LoggerThread.this
和LogService.this
),因此@GuardedBy("this")
不反映現(xiàn)實。

紫衣仙女
TA貢獻1839條經(jīng)驗 獲得超15個贊
this
指的是直接封閉類的當前實例。JLS #15.8.4 .
從邏輯上講,它應(yīng)該引用 LogService 以便同步工作,但從語義上講,它似乎指的是 LoggerThread。
正確的。這是一個錯誤。
添加回答
舉報
0/150
提交
取消