1.volatile 能保证内存可见性
volatile 修饰的变量, 能够保证 "内存可见性".
代码在写入 volatile 修饰的变量的时候,
代码在读取 volatile 修饰的变量的时候
前面我们讨论内存可见性时说了, 直接访问工作内存(实际是 CPU 的寄存器或者 CPU 的缓存), 速度非常快, 但是可能出现数据不一致的情况.加上 volatile , 强制读写内存. 速度是慢了, 但是数据变的更准确了.
2.代码示例
package thread3;import java.util.Scanner;class Counter {public int flag = 0;
}public class Test3 {public static void main(String[] args) {Counter counter = new Counter();Thread t1 = new Thread(() -> {while (counter.flag == 0) {}System.out.println("循环结束!");});Thread t2 = new Thread(() -> {Scanner scanner = new Scanner(System.in);System.out.println("输入一个整数:");counter.flag = scanner.nextInt();});t1.start();t2.start();}
}
如果给 flag 加上 volatile
3.volatile 不保证原子性
volatile 和 synchronized 有着本质的区别. synchronized 既能够保证原子性也能保证内存可见性., volatile 保证的是内存可见性.
package thread3;class Counter1 {volatile public static int count = 0;public void increase() {count++;}
}public class Test4 {public static void main(String[] args) throws InterruptedException {Counter1 counter = new Counter1();Thread t1 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});Thread t2 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});t1.start();t2.start();t1.join();t2.join();System.out.println(Counter1.count);}
}
此时可以看到, 最终 count 的值仍然无法保证是 100000.
synchronized 也能保证内存可见性
synchronized 既能保证原子性, 也能保证内存可见性.
package thread3;class Counter1 {public static int count = 0;public void increase() {count++;}
}public class Test4 {public static void main(String[] args) throws InterruptedException {Counter1 counter = new Counter1();Thread t1 = new Thread(() -> {synchronized (counter) {for (int i = 0; i < 50000; i++) {counter.increase();}}});Thread t2 = new Thread(() -> {synchronized (counter) {for (int i = 0; i < 50000; i++) {counter.increase();}}});t1.start();t2.start();t1.join();t2.join();System.out.println(Counter1.count);}
}