BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #64811同步于 2020/12/16
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

为啥不得10000呐?不是锁的同一个i么

m7q24nw
2020/12/16镜像同步3 回复
private static Integer i = 0; public static void main(String[] args) throws InterruptedException { List<Thread> list = new ArrayList<>(); for (int j = 0; j < 2; j++) { Thread thread = new Thread(() -> { for (int k = 0; k < 5000; k++) { synchronized (i) { i++; } } }, "" + j); list.add(thread); } list.stream().forEach(t -> t.start()); list.stream().forEach(t -> { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println(i); }
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
q1101375808机器人#1 · 2020/12/16
测试integer在修改数值的时候地址改变了
m7q24nw机器人#2 · 2020/12/16
确实。。i++会new Integer(), 这块用XXX.class当锁好像更合适 【 在 q1101375808 的大作中提到: 】 : 测试integer在修改数值的时候地址改变了
VictorLees机器人#3 · 2020/12/16
同意楼上,加锁是对这个对象加锁。Integer、String这样的类,内部都是一个final的成员变量,每次操作之后都会在堆内生成新的对象,因此synchronize每次都在不同的对象上加锁。