对Integer有过了解的可能知道,Integer i = 0 其中 i 的值 在 [-128,127] 是缓存起来的,在JVM中的只有一份。
那就是说 [-128,127] 的值 其实都是共享变量,而在多线程中,只有共享变量才有多线程安全问题。对一个共享变量加锁的话就会导致访问访问该变量的多线程竞争。
看下面例子:
import java.util.concurrent.TimeUnit;
public class TestThread2 {
private Integer i = 127 ;
private Integer j = 127;
public void test1(){
synchronized (i){
try {
System.out.println("test1............");
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void test2(){
synchronized (j){
try {
System.out.println("test2............");
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TestThread2 testThread1 = new TestThread2();
new Thread(() -> {
testThread1.test1();
}).start();
new Thread(() -> {
testThread1.test2();
}).start();
}
}
创建了二个线程分别访问i,j 开始想的是这二个方法分别由二个线程执行,由于锁定的是不同变量i,j(其实是一个)
那就不会造成阻塞,可是结果是 打印 "test1.........." 后过了 10秒才打印出 "test2.........."
很疑惑!!!!,才想起原来 Integer i = 127 i 是共享数据,所以 二个方法其实锁的是一个变量 才会阻塞
这里把 i ,j 设置为 其他区间的数 或者使用 new Integer(127),就会发现二个方法立马打印了。
xxxx