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对象就变化了,这样就会失效的,所以一般都选择独立的对象
022020-12-21
相似问题