给Integer对象加锁的错误方式

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);
    }
}
原文地址:https://www.cnblogs.com/java-spring/p/8327831.html