synchronized(object)在代码块中使用了object,synchronized就无效了

来源:7-3 应用场景_

慕勒7424583

2020-12-13

public class PrintOddEvenSync {
    private static Integer count = 0;
   // private static Integer lock = 0;

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (count) {
                    System.out.println(Thread.currentThread().getName() + "获取锁");
                    while (count < 100) {
                        System.out.println(Thread.currentThread().getName() + "分析偶数:count=" + count);
                        if (count % 2 == 0) {
                            System.out.println("偶数:" + count);
                            count++;
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + "释放锁");
                }
            }
        },"thread1:").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (count) {
                    System.out.println(Thread.currentThread().getName() + "获取锁");
                    while (count < 100) {
                        System.out.println(Thread.currentThread().getName() + "分析奇数:count=" + count);
                        if (count % 2 == 1) {
                            System.out.println("奇数:" + count);
                            count++;
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + "释放锁");
                }
            }
        },"thread2:").start();
    }
}

图片描述图片描述

不使用count作为锁,代码是正常的,使用了count,synchronized就好像无效了,不清楚为什么,老师能解释一下吗

写回答

1回答

悟空

2020-12-13

因为使用后,count对象就变化了,这样就会失效的,所以一般都选择独立的对象

0
2
悟空
回复
慕勒7424583
可以看一下这个:https://stackoverflow.com/questions/40645658/synchronizing-on-an-object-and-changing-the-reference
2020-12-21
共2条回复

深度解密Java并发工具,精通JUC,成为并发多面手

JUC全方位讲解,构建并发工具类知识体系

1599 学习 · 573 问题

查看课程

相似问题