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);

        }
    }
}

输出

总结

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

相关推荐
小满zs3 小时前
Go语言第十八章(架构设计)
后端·go
若亦_3 小时前
Java中关于this的三种用法
java·开发语言·intellij-idea
山甫aa4 小时前
锁一篇搞定:乐观锁、悲观锁、CAS、数据库锁与分布式锁【从零开始的 Web 后端学习】
java·数据库·分布式·后端·学习·web
软件技术NINI4 小时前
基于SpringBoot和Vue的博物馆预约平台管理系统的设计与实现
java·毕业设计·毕设
IT_陈寒4 小时前
Java开发实战:从入门到精通
前端·人工智能·后端
jktantan4 小时前
注解式脱敏:用 Jackson 的 ContextualSerializer 做字段级策略(一)
spring boot·后端·算法·spring cloud·系统架构
独泪了无痕13 小时前
探索Pinyin4j-Java中的拼音转换利器
java·后端
码事漫谈13 小时前
从 Coze 居然要下线了说起
后端
道尔柯南14 小时前
C++ string 类详解:从常用接口到深拷贝,彻底掌握字符串处理
android·java·c++
想不到一个好的ID14 小时前
智能体开发
后端