首页 > 其他 > 详细

使用字符串出现死锁

时间:2019-12-30 14:00:46      阅读:86      评论:0      收藏:0      [点我收藏+]

模拟案例:

/**
 * @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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!