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

  • 相关阅读:
    JWPlayer Uncaught Error: Invalid SRT file
    京东电商API
    map, string 强大的STL
    VFL演示样例
    sizeof小览
    Java中httpClient中三种超时设置
    Windows下Mysql5.6启用监控执行脚本的日志
    实时监控MySql状态
    实时监控mysql数据库变化
    SVN命令使用详解
  • 原文地址:https://www.cnblogs.com/liuwentian/p/3117233.html
Copyright © 2011-2022 走看看