gpt4 book ai didi

java - 在 list 7.15 的 "Concurrency in Practice"中,内部类和外部类如何在 "this"上同步?

转载 作者:搜寻专家 更新时间:2023-11-01 03:00:00 25 4
gpt4 key购买 nike

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();
}
}
}
}

这是“Java 并发实践”一书中的 list 7.15。我不明白同步在那里是如何工作的。为什么内部类和外部类在访问字段的不同对象上同步?这个错误是内部类必须使用同步(LogService.this)吗?或者我完全误解了同步的工作原理?

最佳答案

是书上的错误,列在the errata

p.154: In Listing 7.15, the last two synchronized (this) lines should read synchronized (LogService.this).

关于java - 在 list 7.15 的 "Concurrency in Practice"中,内部类和外部类如何在 "this"上同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37960878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com