1. 程式人生 > >多執行緒 之死鎖

多執行緒 之死鎖

死鎖:同步中巢狀同步。

class  Test  implements  Runnable//多執行緒的表現形式

{

         private  boolean  flag;//定義一個標誌

         Test(boolean flag)//建構函式

             {

                      this.flag=flag;

             }

          public   void   run()//定義run方法

            {

                     while(true)

                          {

                                  if(flag){

                                             synchronized(MyLock.locka)

                                                     {

                                                             synchronized(MyLock.lockb)

                                                                   {

                                                                                   System.out.println(" if  lockb");

                                                                  }

                                                     }

                                           }

                                 else

                                      {

                                                 while(true)

                            {

                                  if(flag){

                                             synchronized(MyLock.lockb)

                                                     {

                                                             synchronized(MyLock.locka)

                                                                   {

                                                                                   System.out.println(" if  locka");

                                                                  }

                                                     }

                                           }

                                      }

                          }

            }

}

class  MyLock

{

            static   Object  locka=new Object();

            static  Object   lockb=new Object();

}

class  DeadLockTest{

             public  static  void  main(String[] args)

                    {

                              Thread t1=new  Thread(new  Test(true));

                              Thread t2=new  Thread(new  Test(false));

                               t1.start();

                               t2.start();

                   }

}