[英]Java Concurrency in Practice "Listing 7.1. Using a volatile field to hold cancellation state.". synchronized for visibility?
我正在閱讀 Java Concurrency in Practice 並遇到以下代碼片段。 我認為synchronized
的用法是為了可見性(讓調用generator.get()
的線程看到最新的primes
),因為PrimeGenerator
任務是由一個線程執行的,內部primes
不與其他線程共享。
我對嗎?
清單 7.1。 使用 volatile 字段來保持取消狀態。
@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);
}
}
清單 7.2。 生成一秒鍾的質數。
List<BigInteger> aSecondOfPrimes() throws InterruptedException {
PrimeGenerator generator = new PrimeGenerator();
new Thread(generator).start();
try {
SECONDS.sleep(1);
} finally {
generator.cancel();
}
return generator.get();
}
我認為使用synchronized
有兩個目的。
primes
變化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.