请把小熊还给我& 2023-01-30 14:03 采纳率: 80%
浏览 29

java中synchronized可见性问题

java中synchronized可见性问题
同步代码块不是说能保证可见性吗 怎么还线程0感知不到total=1

img

  • 写回答

3条回答 默认 最新

  • 小飞LOVE霞 2023-01-30 14:52
    关注
    
    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();
        }
    }
    
    
    
    评论

报告相同问题?

问题事件

  • 修改了问题 1月30日
  • 创建了问题 1月30日