欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java并发编程:volatile关键字解析

程序员文章站 2022-07-12 18:43:51
...
Java并发编程:volatile关键字解析
https://www.cnblogs.com/dolphin0520/p/3920373.html

采用synchronized:
采用Lock:
采用AtomicInteger:

https://www.ibm.com/developerworks/cn/java/j-jtp06197.html

清单 2. 将 volatile 变量作为状态标志使用
volatile boolean shutdownRequested;
...

public void shutdown() { shutdownRequested = true; }

public void doWork() {
    while (!shutdownRequested) {
        // do stuff
    }
}

清单 6. 结合使用 volatile 和 synchronized 实现 “开销较低的读-写锁”
@ThreadSafe
public class CheesyCounter {
    // Employs the cheap read-write lock trick
    // All mutative operations MUST be done with the 'this' lock held
    @GuardedBy("this") private volatile int value;

    public int getValue() { return value; }

    public synchronized int increment() {
        return value++;
    }
}




相关标签: volatile