简单的Java1.4版synchronized多线程的死锁演示

来源:互联网 发布:管家婆sql 安装教程 编辑:程序博客网 时间:2024/05/16 10:55

尽量避开死锁是开发的宗旨,因为死锁不是程序错误,是设计错误,一旦出现线程死锁,很难分析出来

常见的线程死锁就是同步模块的嵌套,面试常用

以下是线程死锁示例:

class Test implements Runnable{    boolean flag = true;    Object obj = new Object();//锁    public void run()    {        if (flag)        {            while(true)            {                //使用同步代码块                synchronized(obj)                {                     //同步模块嵌套                    synMethod();                }            }        }        else         {   //用于进城切换演示            while(true)            {                synMethod();            }        }    }    synchronized void synMethod()    {        //同步模块嵌套        synchronized(obj)        {            func();        }    }    void func()    {            System.out.println(Thread.currentThread().getName()+"获取资源");    }}class DeadLockDemo{    public static void main(String[] args)     {        Test l= new Test();        Thread t1 = new Thread(l);        Thread t2 = new Thread(l);        t1.start();        try{    Thread.sleep(10);}catch (InterruptedException ex){}//为了显示效果而写的主进程休息10ms        l.flag = false;//线程切换        t2.start();    }}

封装了线程切换更为简洁:

class Test implements Runnable{    private boolean flag;    Test(boolean flag)    {        this.flag = flag;    }    public void run()    {        if (flag)        {            while(true)            {                synchronized(LockObject.lockTrue)                {                synchronized(LockObject.lockFalse)                    {                    System.out.println(Thread.currentThread().getName()+" ---->run ");                    }                }            }        }        else         {            while(true)            {                synchronized(LockObject.lockFalse)                {                    synchronized(LockObject.lockTrue)                        {                            System.out.println(Thread.currentThread().getName()+" ---->run ");                        }                }            }        }    }}class LockObject{    public static final Object lockTrue = new Object();    public static final Object lockFalse = new Object();}class DeadLockDemo{    public static void main(String[] args)     {        Test l1 = new Test(true);        Test l2 = new Test(false);        Thread t1 = new Thread(l1);        Thread t2 = new Thread(l2);        t1.start();        t2.start();    }}
1 0
原创粉丝点击