第一章 Java编程基础 (30讲)
06 | HelloWorld程序编译和运行(Windows)
08 | IntelliJ IDEA集成开发环境的安装和使用(macOS)
09 | IntelliJ IDEA集成开发环境的安装和使用(Windows)
第二章 Java面向对象编程 (74讲)
第三章 Java中的异常处理 (9讲)
第四章 Java中的常用工具类和新语法 (22讲)
第五章 Java中的线程 (19讲)
强制从内存获取数据
public class AccessMemoryVolatile {
public volatile long counterV = 0;
public long counter = 0;
public static void main(String[] args) {
int loopCount = Integer.MAX_VALUE / 30;
// TODO 只是为了演示 volatile 每次访问都要直达内存,不能使用缓存,所以耗费的时间略多
AccessMemoryVolatile accessMemoryVolatile = new AccessMemoryVolatile();
Thread volatileAdder = new Thread(() -> {
long start = System.currentTimeMillis();
for (int i = 0; i < loopCount; i++) {
accessMemoryVolatile.counterV++;
}
System.out.println("volatile adder takes " + (System.currentTimeMillis() - start));
});
volatileAdder.start();
Thread justAdder = new Thread(() -> {
long start = System.currentTimeMillis();
for (int i = 0; i < loopCount; i++) {
accessMemoryVolatile.counter++;
}
System.out.println("simple adder takes " + (System.currentTimeMillis() - start));
});
justAdder.start();
}
}
影响指令重排
package com.geekbang.learnvolatile;
public class VolatileAppMain {
public static void main(String[] args) {
DataHolder dataHolder = new DataHolder();
Thread operator = new Thread(() -> {
while (true) {
dataHolder.operateData();
}
});
operator.start();
Thread checker = new Thread(() -> {
while (true) {
dataHolder.check();
}
});
checker.start();
}
}
第六章 Java编程实战 (16讲)
164 | 如何在Stack Overflow上提问才不会被骂