为了账号安全,请及时绑定邮箱和手机立即绑定

使用此关键字作为并发锁

使用此关键字作为并发锁

SMILET 2021-05-31 16:15:48
在下面的程序中,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 回答

?
慕娘9325324

TA贡献1783条经验 获得超4个赞

thisLoggerThread方法内是指一个LoggerThread实例。
LogService.this指的是外部类。


二者isShutdownreservations通过不同的锁(同步LoggerThread.thisLogService.this),因此@GuardedBy("this")不反映现实。


查看完整回答
反对 回复 2021-06-02
?
紫衣仙女

TA贡献1839条经验 获得超15个赞

this指的是直接封闭类的当前实例。JLS #15.8.4 .

从逻辑上讲,它应该引用 LogService 以便同步工作,但从语义上讲,它似乎指的是 LoggerThread。

正确的。这是一个错误。


查看完整回答
反对 回复 2021-06-02
  • 3 回答
  • 0 关注
  • 129 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信