volatile
1.保证此变量对所有的线程的可见性,这里的“可见性”。
2.防止指令重排
测试多线程的可见效
package com.jarvis.reference;
/**
* @author jinzhaopo
* @date 2023-12-22 09:43
*/
public class VolatileTest {
private static boolean judge = false;
private static volatile boolean volatileJudge = false;
/**
* 测试可见性
*/
public static void visibility() {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
judge = true;
volatileJudge = true;
System.out.println("set judge and volatileJudge = true");
}
}).start();
new Thread(new Runnable() {
public void run() {
while (!judge) {
}
System.out.println("judge = true");
}
}).start();
new Thread(new Runnable() {
public void run() {
while (!volatileJudge) {
}
System.out.println("volatileJudge = true");
}
}).start();
}
public static void main(String[] args) {
visibility();
}
}