codeMonkey_sun 2017-07-13 09:06 采纳率: 50%
浏览 1008
已采纳

java 线程同步 synchronized

public class Test {

private int i = 0;

public Test() {

}

public int getI() {
    return i;
}

public void setI(int i) {
    this.i = i;
}

public static void main(String[] args) throws InterruptedException {
    Test t = new Test();
    Thread tt1 = new Thread(new TestThread(t));
    Thread tt2 = new Thread(new TestThread(t));
    Thread tt3 = new Thread(new TestThread(t));
    Thread tt4 = new Thread(new TestThread(t));
    tt1.start();
    tt2.start();
    tt3.start();
    tt4.start();
    tt1.join();
    tt2.join();
    tt3.join();
    tt4.join();
    System.out.println("ok");
}

}

public class TestThread implements Runnable {

Test t;

public TestThread (Test t) {
    this.t = t;
}

public synchronized void run() {
    t.setI(t.getI() + 10);
    System.out.println(t.getI());
}

}

 输出:
30
30
40
40
ok

问题 :
想要得到输出10 20 30 40,为什么加了synchronized还不行

  • 写回答

2条回答 默认 最新

  • 逗比123号 2017-07-13 09:15
    关注
     public  void run() {
        synchronized(t){
            t.setI(t.getI() + 10);
            System.out.println(t.getI());
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作