• 利用synchronized解析死锁的一种形成方式


    代码

    import ...

    public class Test{

    private static Object o1=new Object();

    private static Object o2=new Object();

    public static void main(String[] args){

    new Thread(

    new Runnable(){

    @override

    public void run(){

    synchronized(o1){

    System.out.println("get o1");

    try{Thread.sleep(100);}catch(ThreadInterruptException e){System.out.println(e.getMessage();}

    }

    synchronized(o2){System.out.println("get o2");}

    }

    ).start();

    new Thread(

    new Runnable(){

    @override

    public void run(){

    synchronized(o2){

    System.out.println("get o2");

    try{Thread.sleep(100);}catch(ThreadInterruptException e){System.out.println(e.getMessage();}

    }

    synchronized(o1){System.out.println("get o1");}

    }

    ).start();

    }

    }

     

    分析

    在第一个线程开始睡眠的时候并没有释放锁,第二个线程后睡,所以第一个线程先醒,醒了以后不会释放锁,因为下述还是synchronized,它属于可重入锁,也就是说锁会从第一个资源过渡到第二个资源,只有请求到第二个资源的时候才会过渡锁。现在第二个线程醒了,同理它也不会释放锁,因为它下面也是synchronized,它也需要请求到资源以后过渡锁。死锁形成。

  • 相关阅读:
    NPM
    Angular2.0快速开始
    AngularJS常用插件与指令收集
    Linq 操作基础
    SQL Server2008 with(lock)用法
    SQL Server2008 MERGE指令用法
    SQL Server2008 表旋转(pivot)技术
    ef to sqlite 实际开发问题终极解决方法
    windows控件常用缩写
    SQL 查询总结
  • 原文地址:https://www.cnblogs.com/riverer/p/2020_06_20_001.html
Copyright © 2020-2023  润新知