gpt4 book ai didi

Java并发实践 "Listing 7.1. Using a volatile field to hold cancellation state."。同步可见性?

转载 作者:行者123 更新时间:2023-12-01 19:06:38 25 4
gpt4 key购买 nike

我正在阅读 Java 并发实践并遇到以下代码片段。我认为使用synchronized是为了可见性(让调用generator.get()的线程看到最新的primes),因为任务PrimeGenerator 由单个线程执行,内部 primes 不与其他线程共享。

我说得对吗?

Listing 7.1. Using a volatile field to hold cancellation state.

@ThreadSafe
public class PrimeGenerator implements Runnable {
@GuardedBy("this")
private final List<BigInteger> primes
= new ArrayList<BigInteger>();
private volatile boolean cancelled;

public void run() {
BigInteger p = BigInteger.ONE;
while (!cancelled) {
p = p.nextProbablePrime();
synchronized (this) {
primes.add(p);
}
}
}

public void cancel() {
cancelled = true;
}

public synchronized List<BigInteger> get() {
return new ArrayList<BigInteger>(primes);
}
}

Listing 7.2. Generating a second’s worth of prime numbers.

List<BigInteger> aSecondOfPrimes() throws InterruptedException {
PrimeGenerator generator = new PrimeGenerator();
new Thread(generator).start();
try {
SECONDS.sleep(1);
} finally {
generator.cancel();
}
return generator.get();
}

最佳答案

我认为使用synchronized有两个目的。

  1. 可见度。让读取线程看到通过添加线程更改的最新素数
  2. 原子性。当读取线程正在读取时,添加线程被阻塞,反之亦然。

关于Java并发实践 "Listing 7.1. Using a volatile field to hold cancellation state."。同步可见性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59542382/

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