package com.thread.test;

public class BadLockOnInteger implements Runnable {

    public static Integer i = 0;// Integer属于不变对象,要想改变,只能重新创建对象

    static BadLockOnInteger instance = new BadLockOnInteger();

    public void run() {
        for (int j = 0; j < 10000000; j++) {
            synchronized (i) {// 因此给i(Integer对象)加锁,两个线程每次加锁都有可能加在不同的对象上,这就导致输出结果远小于20000000
                i++;// 解决方案是给instance加锁,这就就可以保证两个线程都是在同一个对象上加的锁,输出结果就会是20000000
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(instance);
        Thread t2 = new Thread(instance);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(i);
    }
}

 

相关文章:

  • 2021-11-01
  • 2021-08-16
  • 2021-08-21
  • 2022-12-23
  • 2021-06-23
  • 2021-12-12
猜你喜欢
  • 2022-01-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-20
相关资源
相似解决方案