zoukankan      html  css  js  c++  java
  • Java死锁

    class Test
    {
        public static void main(String[] args)
        {
            Demo d1=new Demo(true);
            Demo d2=new Demo(false);
            Thread t1=new Thread(d1);
            Thread t2=new Thread(d2);
            t1.start();
            t2.start();
        }
    }

    class MyLock
    {
        public static final Object locka=new Object();
        public static final Object lockb=new Object();
    }

    class Demo implements Runnable
    {
        private boolean flag;
        private int num=100;
        public Demo(boolean flag)
        {
            this.flag=flag;
        }
        public void run()
        {
            if(this.flag)
            {
                while(true)
                {
                    synchronized(MyLock.locka)
                    {
                        System.out.println(Thread.currentThread().getName()+"...if...locka-->num::"+this.num--);
                        synchronized(MyLock.lockb)
                        {
                            System.out.println(Thread.currentThread().getName()+"...if...lockb-->num::"+this.num--);
                        }
                    }
                }
            }
            else
            {
                while(true)
                {
                    synchronized(MyLock.lockb)
                    {
                        System.out.println(Thread.currentThread().getName()+"...else...lockb-->num::"+this.num--);
                        synchronized(MyLock.locka)
                        {
                            System.out.println(Thread.currentThread().getName()+"...else...locka-->num::"+this.num--);
                        }
                    }
                }
            }
        }
    }

    当t1线程手持A锁,要B锁时,此时,刚刚好线程t2手持B锁要A锁。双方均等的对方锁的释放。出现死锁情况。

  • 相关阅读:
    Spring配置文件中的那些标签意味着什么(持续更新)
    转 spring配置文件
    Web.xml配置详解之context-param
    web.xml 中的listener、 filter、servlet 加载顺序及其详解
    spring mvc 中web.xml配置信息解释
    转 一个web项目web.xml的配置中<context-param>配置作用
    在web.xml中通过contextConfigLocation配置spring
    (转)web.xml中的contextConfigLocation在spring中的作用
    Android菜鸟的成长笔记(20)——IntentService
    PhotoSwipe源码解读系列(二)
  • 原文地址:https://www.cnblogs.com/liuwentian/p/3117233.html
Copyright © 2011-2022 走看看