synchronized字符串常量

前言

synchronized 锁字符串常量语法上可行,但是不推荐

synchronized字符串常量

csharp 复制代码
public class StringSyncDemo {

    static void main() throws InterruptedException {
        String str = "aa";
        Thread thread1 = Thread.startVirtualThread(() -> {
            hello(str);
        });
        Thread thread2 = Thread.startVirtualThread(() -> {
            hello("aa");
        });
        thread1.join();
        thread2.join();
    }

    public static void hello(String str) {
        synchronized (str) {
            System.out.println(Thread.currentThread() + ":进入锁===============" + str);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread() + ":结束锁===============" + str);

        }
    }
}

输出

java 复制代码
package cn.com.ut.sept.sync;

public class StringSyncDemo {

    static void main() throws InterruptedException {
        String str = "aa";
        Thread thread1 = Thread.startVirtualThread(() -> {
            hello(str);
        });
        Thread thread2 = Thread.startVirtualThread(() -> {
            hello("bb");
        });
        thread1.join();
        thread2.join();
    }

    public static void hello(String str) {
        synchronized (str) {
            System.out.println(Thread.currentThread() + ":进入锁===============" + str);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread() + ":结束锁===============" + str);

        }
    }
}

输出

总结

同一个字符串常量都会锁同一个对象。不同模块、第三方库、框架内部如果恰好也用了同一个字符串常量,就可能产生意外竞争,甚至死锁

相关推荐
长谷深风1112 小时前
Tool与Skill:AI能力设计的分水岭
java·人工智能·ai·大模型·aiagent
m0_587383002 小时前
广州24小时自助健身房解决方案实战指南与系统部署要点
java·spring·小程序·架构·需求分析
Escalating_xu2 小时前
【C 语言】深入理解指针(1·下):指针运算、野指针、assert 与传址实战
java·c语言·开发语言
周杰偷奶茶2 小时前
【Java】数据类型与变量
java·开发语言
code斗2 小时前
Java数据结构:堆详解
java·开发语言·数据结构
颜进强2 小时前
16 · NestJS LifecycleEvents 生命周期事件:五个钩子、三条边界,和 rag-server 的优雅停机
前端·后端·ai编程
重生之小比特2 小时前
【C++进阶】map和set
java·开发语言·c++
GetcharZp3 小时前
定位不再一个个吐坐标:英伟达 LocateAnything 上手全攻略
后端
需要8263 小时前
分布式事务:Seata AT/TCC/SAGA 的取舍与踩坑
java·spring boot·分布式·spring·spring cloud