1.可见性(被volatile修饰的变量值改变,对其他线程可见)
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
myThread.setFlag(false);
}
static class MyThread extends Thread {
volatile boolean flag = true;
@Override
public void run() {
while (flag) {
System.out.println(Thread.currentThread().getName() + " running.");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void setFlag(boolean flag) {
System.out.println(Thread.currentThread().getName() + " change flag.");
this.flag = flag;
}
}
2.禁止指令重排
比如以下flag没有被volatile修饰,所以(configInfo = “change”;flag = false;) 指令顺序可能是先改变flag值,这样程序就会出现问题
static boolean flag = true;
static String configInfo = "origin";
public static void main(String[] args) throws Exception {
Thread threadA = new Thread(() -> {
configInfo = "change";
flag = false;
});
Thread threadB = new Thread(() -> {
while (flag) {
}
System.out.println(Thread.currentThread().getName() + " " + configInfo);
});
threadA.start();
threadB.start();
threadA.join();
threadB.join();
}