Java并发编程:volatile关键字解析
程序员文章站
2022-07-15 15:07:46
...
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++;
}
}
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++;
}
}
上一篇: win10安装OpenSSL及简单的使用
下一篇: 架构师技术图谱,助你早日成为架构师