死锁

来源:互联网 发布:java中的转义字符 编辑:程序博客网 时间:2024/06/11 16:09

转载地址:http://blog.csdn.net/qq_24653023/article/details/51764451


死锁的情况 

千万不要在使用中造成这种情况



[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package day13;  
  2.   
  3. class Test implements Runnable  
  4. {  
  5.     private boolean flag;  
  6.     Test(boolean flag)  
  7.     {  
  8.         this.flag = flag;  
  9.     }  
  10.   
  11.     public void run()  
  12.     {  
  13.           
  14.         if(flag)  
  15.         {  
  16.             while(true)  
  17.                 synchronized(MyLock.locka)  
  18.                 {  
  19.                     System.out.println(Thread.currentThread().getName()+"..if   locka....");  
  20.                     synchronized(MyLock.lockb)              {  
  21.                           
  22.                         System.out.println(Thread.currentThread().getName()+"..if   lockb....");  
  23.                     }  
  24.                 }  
  25.         }  
  26.         else  
  27.         {  
  28.             while(true)           
  29.                 synchronized(MyLock.lockb)  
  30.                 {  
  31.                     System.out.println(Thread.currentThread().getName()+"..else  lockb....");  
  32.                     synchronized(MyLock.locka)  
  33.                     {  
  34.                         System.out.println(Thread.currentThread().getName()+"..else   locka....");  
  35.                     }  
  36.                 }  
  37.         }  
  38.   
  39.     }  
  40.   
  41. }  
  42. class MyLock  
  43. {  
  44.     public static final Object locka = new Object();  
  45.     public static final Object lockb = new Object();  
  46. }  
  47. public class DeadLockTest   
  48. {  
  49.     public static void main(String[] args)   
  50.     {  
  51.         Test a = new Test(true);  
  52.         Test b = new Test(false);  
  53.   
  54.         Thread t1 = new Thread(a);  
  55.         Thread t2 = new Thread(b);  
  56.         t1.start();  
  57.         t2.start();  
  58.     }  
  59. }  

0 0