使用此关键字作为并发锁

在下面的程序中,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();

            }

        }

    }

}

感谢您的帮助


SMILET
浏览 130回答 3
3回答

慕娘9325324

thisLoggerThread方法内是指一个LoggerThread实例。LogService.this指的是外部类。二者isShutdown并reservations通过不同的锁(同步LoggerThread.this和LogService.this),因此@GuardedBy("this")不反映现实。

紫衣仙女

this指的是直接封闭类的当前实例。JLS #15.8.4&nbsp;.从逻辑上讲,它应该引用 LogService 以便同步工作,但从语义上讲,它似乎指的是 LoggerThread。正确的。这是一个错误。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java