zoukankan      html  css  js  c++  java
  • 使用字符串出现死锁

    模拟案例:

    /**
     * @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”字符串地址,即俩个线程的锁是同一个地址,所以会出现死锁的情况

    当你发现自己的才华撑不起野心时,就请安静下来学习吧
  • 相关阅读:
    python中字典一键多相同值反转技巧
    win10下安装mysql
    上台阶问题的具体走法用python来实现
    桥接模式
    适配器模式
    多线程中lock的使用
    原型模式
    多线程
    建造者模式
    代理模式
  • 原文地址:https://www.cnblogs.com/smallVampire/p/12118711.html
Copyright © 2011-2022 走看看