码迷,mamicode.com
首页 > 编程语言 > 详细

Java 死锁

时间:2018-01-18 11:43:29      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:同步   string   col   pre   output   sync   常见   int   ble   

/*
死锁:常见情景之一:同步的嵌套。
*/

class Test implements Runnable
{
    private boolean flag;
    Test(boolean flag)
    {
        this.flag = flag;
    }

    public void run()
    {
        if(flag)
        {
            while(true)
                synchronized(MyLock.locka)
                {
                    System.out.println(Thread.currentThread().getName()+"..if   locka....");
                    synchronized(MyLock.lockb)                {
                        
                        System.out.println(Thread.currentThread().getName()+"..if   lockb....");
                    }
                }
        }
        else
        {
            while(true)            
                synchronized(MyLock.lockb)
                {
                    System.out.println(Thread.currentThread().getName()+"..else  lockb....");
                    synchronized(MyLock.locka)
                    {
                        System.out.println(Thread.currentThread().getName()+"..else   locka....");
                    }
                }
        }
    }
}

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

class SynFunctionLockDemo 
{
    public static void main(String[] args) 
    {
        Test a = new Test(true);
        Test b = new Test(false);

        Thread t1 = new Thread(a);
        Thread t2 = new Thread(b);
        t1.start();
        t2.start();
    }
}
Output:
Thread-0..if   locka....
Thread-1..else  lockb....

Java 死锁

标签:同步   string   col   pre   output   sync   常见   int   ble   

原文地址:https://www.cnblogs.com/xiarongjin/p/8309024.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!