大家好,又见面了,我是你们的朋友全栈君。
小编参考了吃透Java并发:volatile是怎么保证可见性的这篇博客,在此对博主进行感谢! volatile 修饰的成员变量在每次被线程访问时,都强制从共享内存中重新读取该成员变量的值。而且,当成员变量发生变化时,会强制线程将变化值回写到共享内存。这样在任何时刻,两个不同的线程总是看到某个成员变量的同一个值。
public class MainDemo {
// private static int a = 0;
private static volatile int a = 0;
private static int number = 0;
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (a == 0) {
}
System.out.println("T1得知a = 1");
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
a = 1;
System.out.println("T2修改a = 1");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
总结: 从上面的 demo中可以看出,变量a是可见的。
新建 Main
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Main {
private static int a = 0;
// private static volatile int a = 0;
private static int number = 0;
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (a == 0) {
// log.info("t1在运行"); // 非volatile 修饰的也可见
// System.out.println("println 打印 t1在运行"); // synchronized 非volatile 修饰的也可见
try {
Thread.sleep(10); // 非volatile 修饰的也可见
} catch (InterruptedException e) {
e.printStackTrace();
}
// number++; // 非volatile不可见
}
System.out.println("T1得知a = 1");
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
a = 1;
System.out.println("T2修改a = 1");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
注意以下情况:
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/161282.html原文链接:https://javaforall.cn