多线程(死锁)

线程死锁的原因:

同步中嵌套同步,但是锁却不同

死锁演示(DeadLockDemo):

class Test implements Runnable
{
    private boolean flag;
    //构造函数中传入标记的值,用来操作run方法中的if else循环
    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
{
    static Object lockA = new Object();
    static Object lockB = new Object();
}

class  DeadLockTest
{
    public static void main(String[] args) 
    {
        //传入true使其在if循环中
        Thread t1 = new Thread(new Test(true));
        //传入false使其在if循环中
        Thread t2 = new Thread(new Test(false));
        t1.start();
        t2.start();
    }
}
DeadLockDemo

 

posted @ 2015-10-23 22:46  坚持坚持再坚持  阅读(157)  评论(0编辑  收藏  举报