java 实现死锁

时间:2014-10-07 00:07:01   收藏:0   阅读:362
package 线程安全的讨论;
class DThread implements Runnable
{
    private Object o1=null;
    private Object o2=null;
    public DThread(Object o1,Object o2)
    {
        this.o1=o1;
        this.o2=o2;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
              synchronized(o1)
              {
                  try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                  synchronized(o2)
                  {
                      System.out.println("突破两道防线,进来啊,哈哈"+Thread.currentThread().getId());
                  }
                  
                  
              }
    }
    
    
    }

public class DeadLockTest {
    public static void main(String args[])
    {
        System.out.println("死锁检测");
        Object o1=new Object();
        Object o2=new Object();
        //开启10个线程,按照1,2获得锁。
        for(int i=0;i<100;i++)
        {
            new Thread(new DThread(o1,o2)).start();;
        }
        //按照1,0获得锁
        for(int i=0;i<100;i++)
        {
            new Thread(new DThread(o2,o1)).start();;
        }
        for(int i=0;i<100;i++)
        {
            new Thread(new DThread(o1,o2)).start();;
        }
        
        
    }

}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!