前言
synchronized 锁字符串常量语法上可行,但是不推荐
synchronized字符串常量
1public class StringSyncDemo { 2 3 static void main() throws InterruptedException { 4 String str = "aa"; 5 Thread thread1 = Thread.startVirtualThread(() -> { 6 hello(str); 7 }); 8 Thread thread2 = Thread.startVirtualThread(() -> { 9 hello("aa"); 10 }); 11 thread1.join(); 12 thread2.join(); 13 } 14 15 public static void hello(String str) { 16 synchronized (str) { 17 System.out.println(Thread.currentThread() + ":进入锁===============" + str); 18 try { 19 Thread.sleep(3000); 20 } catch (InterruptedException e) { 21 throw new RuntimeException(e); 22 } 23 System.out.println(Thread.currentThread() + ":结束锁===============" + str); 24 25 } 26 } 27} 28
输出
1package cn.com.ut.sept.sync; 2 3public class StringSyncDemo { 4 5 static void main() throws InterruptedException { 6 String str = "aa"; 7 Thread thread1 = Thread.startVirtualThread(() -> { 8 hello(str); 9 }); 10 Thread thread2 = Thread.startVirtualThread(() -> { 11 hello("bb"); 12 }); 13 thread1.join(); 14 thread2.join(); 15 } 16 17 public static void hello(String str) { 18 synchronized (str) { 19 System.out.println(Thread.currentThread() + ":进入锁===============" + str); 20 try { 21 Thread.sleep(3000); 22 } catch (InterruptedException e) { 23 throw new RuntimeException(e); 24 } 25 System.out.println(Thread.currentThread() + ":结束锁===============" + str); 26 27 } 28 } 29} 30
输出
总结
同一个字符串常量都会锁同一个对象。不同模块、第三方库、框架内部如果恰好也用了同一个字符串常量,就可能产生意外竞争,甚至死锁
参考文档
《synchronized字符串常量》 是转载文章,点击查看原文。