---
title: "Java并发编程：volatile关键字解析"
author: "maxer025"
date: "2019-10-23T16:18:58Z"
tags: []
categories: ["互联网"]
slug: "java-volatile"
draft: false
lastmod: "2019-10-23T16:18:58Z"
id: 2509178
url: "https://maxer025.iteye.com/blog/2509178"
---

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++;
    }
}