云敛容 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重新创建对象。其实已经不是一个对象了。

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料