Java synchronized代码块锁字符串无效的问题解决方案
public static void test(String str) {
synchronized(str) {
System.out.println("进来啦" + str);
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("结束啦" + str);
}
}
public static void test1(String str) {
synchronized(str.intern()) {
System.out.println("进来啦" + str);
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("结束啦" + str);
}
}
public static void test2(int val) {
synchronized(val + "") {
System.out.println("进来啦" + val);
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("结束啦" + val);
}
}
public static void main(String[] args) {
for(int i=0; i<5; i++) {
int b = i;
new Thread(() -> {
test1(b + "");
}).start();
new Thread(() -> {
test1(b + "");
}).start();
}
}