现在的位置: 首页 > 综合 > 正文

经典线程死锁

2012年02月03日 ⁄ 综合 ⁄ 共 692字 ⁄ 字号 评论关闭

代码例子如下:

public class TestDeadLock implements Runnable
{
    public int flag = 1;
    static Object S1 = new Object(), S2=new Object();
    
    public void run()
    {
        System.out.println("flag="+flag);

        if(flag==1)
        {
            synchronized(S1)
            {
                try{
                    Thread.sleep(500);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }

                synchronized(S2)
                {
                    System.out.println("1");
                }
            } 
        }

        if(flag==0)
        {
            synchronized(S2)
            {
                try{
                    Thread.sleep(500);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
                synchronized(S1){
                System.out.println("0");
            }
        }
    }
}

public static void main(String[] args)
{
    TestDeadLock td1=new TestDeadLock();
    TestDeadLock td2=new TestDeadLock();
    td1.flag=1;
    td2.flag=0;
    Thread t1=new Thread(td1);
    Thread t2=new Thread(td2);
    t1.start();
    t2.start();
}

 

原文地址:

http://www.blogjava.net/Werther/archive/2009/03/12/259258.html

抱歉!评论已关闭.