java 实现死锁

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();;

        }

        

        

    }



}

 

你可能感兴趣的:(java)