簡體   English   中英

Java 並發實踐“清單 7.1。使用 volatile 字段來保持取消狀態。”。 同步可見性?

[英]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有兩個目的。

  1. 能見度 通過添加線程,讓閱讀線程看到最新的質primes變化。
  2. 原子性 當讀取線程正在讀取時,添加線程被阻塞,反之亦然。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM