-
内存可见性:当一个线程修改了一个volatile变量的值,其他线程会立即看到这个改变。这是因为volatile关键字会禁止CPU缓存和编译器优化,从而确保每次读取变量时都会直接从主内存中获取最新值,而不是从本地缓存中读取。这样就能确保多个线程之间对变量的操作是同步的。
-
禁止指令重排:volatile关键字还能防止处理器对指令进行重排序。在多线程环境中,如果不使用volatile,编译器和处理器可能会对代码进行重排序,从而影响多线程的正确性。而volatile关键字可以确保指令的执行顺序不被重排,从而保证结果的正确性。
public class VolatileExample {private volatile boolean flag = false;public static void main(String[] args) {VolatileExample example = new VolatileExample();// 线程1new Thread(() -> {for(int i = 0; i < 10; i++) {System.out.println("Thread 1: " + i);example.flag = true;try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}).start();// 线程2new Thread(() -> {for(int i = 0; i < 10; i++) {if(example.flag) {System.out.println("Thread 2: " + i);try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}} else {try {Thread.sleep(75);} catch (InterruptedException e) {e.printStackTrace();}}}}).start();}}
原创文章,作者:速盾高防cdn,如若转载,请注明出处:https://www.sudun.com/ask/76183.html