使用字符串出现死锁

模拟案例:

/**
 * @description: 模拟以字符串为锁出现的死锁
 **/
public class MyStringThread {

    String str1 = "hello";
    String str2 = "hello";

    public void test1(){
        synchronized (str1){
            System.out.println("t1.start----");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t1.end------");
        }
    }

    public void test2(){
        synchronized (str2){
            System.out.println("t2.start----");
        }
    }

    public static void main(String args[]){
        MyStringThread myStringThread =new MyStringThread();
        new Thread(myStringThread::test1,"t1").start();
        new Thread(myStringThread::test2,"t2").start();
    }

}

解释:根据jvm底层架构,str1和str2都指向了堆中的“hello”字符串地址,即俩个线程的锁是同一个地址,所以会出现死锁的情况

当你发现自己的才华撑不起野心时,就请安静下来学习吧
原文地址:https://www.cnblogs.com/smallVampire/p/12118711.html