云敛容 2017-02-06 15:58 采纳率: 33.3%
浏览 2033
已采纳

Java Synchronized(object) 无效

直接贴代码:


public class TestSync implements Runnable {

    Timer timer = new Timer();

    @Override
    public void run() {

        if ("t1".equals(Thread.currentThread().getName())) {
            timer.add(Thread.currentThread().getName());
        } else {
            timer.add2(Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) {
        TestSync test = new TestSync();
        Thread t1 = new Thread(test);
        Thread t2 = new Thread(test);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        t2.start();
    }

}

class Timer {
    private /*static*/ Integer num = 0;

    public void add(String name) {
        synchronized (num) {
            num++;
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
            }
            System.out.println(name + ", num = " + num);
        }
    }

    public void add2(String name) {
        synchronized (num) {
            num++;
            try {
                Thread.sleep(2);
            } catch (InterruptedException e) {
            }
            System.out.println(name + ", num2 = " + num);
        }
    }
}

为什么有时候出来的结果是:
t2, num2 = 2
t1, num = 2

不应该是下面这个吗?
t1, num = 1
t2, num2 = 2

  • 写回答

1条回答 默认 最新

  • 云敛容 2017-02-06 16:20
    关注

    我知道了:因为Integer执行自加操作的时候,是要进行拆箱操作即调用Integer的intValue返回基本类型数据,执行完自增以后,再调用Integer的装箱操作即调用valueOf重新创建对象。其实已经不是一个对象了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏