我们常常在程序中使用多线程来处理任务,这个时候是否正确使用加锁就很重要了,有时候看着代码没啥问题,但是执行起来发现结果并不是看到的那样,比如我们看下面的代码
package me.lishuo;
/**
* @date 2018/7/21 下午5:10
*/
public class WrongLockOnInteger implements Runnable {
public static Integer a=0;
static WrongLockOnInteger wrongLockOnInteger =new WrongLockOnInteger();
public void run(){
for(int j=0;j<1000;j++){
synchronized (a){
a++;
}
}
}
public static void main(String args[]){
try{
Thread thread1=new Thread(wrongLockOnInteger);
Thread thread2=new Thread(wrongLockOnInteger);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.print("a="+a);
}catch (Exception e){
e.printStackTrace();
}
}
}
看着代码感觉执行结果应该是2000,而打印出来的结果却是下面的:
这个时候我们再去看代码,我们对Integer对象a进行加锁,这个时候就有个一个Java基础知识在里面,Integer是不可变对象,是实例对象,对象一但被创建就不能被修改,比如赋值是1,就是1,如果让它变成2,需要重新创建一个Integer对象,
然后下面循环中进行a++,其实这里Java对这个进行了内部转换( Java封箱拆箱) ,其实是执行的这个语句a=Integer.valueOf(a.intValue()+1),我们看下JDK这个方法,这个方法是个工厂方法,它会返回一个Integer实例,因此a++本质是创建一个Integer对象,并将它的引用赋值给a,
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
如此一来我们就知道问题所在了,2个线程在运行期间,每次加锁可能是针对的不同的Integer实例,所以导致问题发生,这个时候我们把synchronized (a)改成synchronized (wrongLockOnInteger)就行了