java中synchronized可见性问题
同步代码块不是说能保证可见性吗 怎么还线程0感知不到total=1
package csdn20230129;
/**
* @Description
* @Author wangFei
* @Date 2023/1/30 10:15
* @Version 1.0
**/
public class Test {
int total = 0;
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
test.a();
test.b();
}
public synchronized void a() {
new Thread(() -> {
System.out.println("a线程 " + Thread.currentThread().getName() + " 执行");
synchronized (this) {
while (total == 0);
System.out.println("a-1-end");
}
}).start();
}
public synchronized void b() {
new Thread(() -> {
System.out.println("b线程 " + Thread.currentThread().getName() + " 执行");
total = 1;
System.out.println("b线程 " + Thread.currentThread().getName() + " 执行完毕,当前total=" + total);
}).start();
}
}
可见性是 强制将主存信息刷到内存,所以这里主线程main 执行完后都会刷到内存中,加synchronized只是然后这个刷到内存操作提前