synchronized字符串常量

85 阅读1分钟

前言

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

synchronized字符串常量

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

        }
    }
}

输出

image.png

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

        }
    }
}

输出

image.png

总结

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