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锁。双方均等的对方锁的释放。出现死锁情况。

  • 相关阅读:
    RHEL双网卡绑定
    图解机房收费系统报表制作的全过程
    linux内存管理机制
    hdu4432 Sum of divisors(数论)
    树和而叉查找树的实现
    49. 面向对象的LotusScript(十五)之Log4Dom下
    HDU 4009 不定根最小树形图
    模拟+二分 poj-1019-Number Sequence
    SQL Server 事务日志传输
    百度开放云java+tomcat部署web项目-小皇帝詹姆斯
  • 原文地址:https://www.cnblogs.com/liuwentian/p/3117233.html
Copyright © 2011-2022 走看看