死锁AB-BA问题

AB-BA经常是造成多线程死锁的最大元凶,具体表现为线程I先后去拿锁A与锁B,然而当去拿锁B时发现已经被另一个线程II拿走,然而线程II拿到锁B后又需要锁A,于是两个线程互相等待在成死锁

 1 public class Main{
 2      public static void main(String[] args){
 3         System.out.println("演示开始");
 4            new Thread(()->{
 5              A.a();
 6            }).start();
 7            new Thread(()->{
 8              B.b();
 9            }).start();
10      }
11 
12      static class A{
13         public static synchronized void a(){
14             try{
15                 Thread.sleep(3000);    
16             }catch(Exception e){
17                 e.printStackTrace();
18             }
19             
20 
21             System.out.println("我拿到锁a了,锁b快到碗里来!");
22 
23             B.b();
24         }
25      }
26 
27      static class B{
28         public static synchronized void b(){
29             System.out.println("我拿到锁b了,锁a快到碗里来!");
30             try{
31                 Thread.sleep(3000);    
32             }catch(Exception e){
33                 e.printStackTrace();
34             }
35             A.a();
36         }
37      }
38  }

猜你喜欢

转载自www.cnblogs.com/shaozhen/p/11127126.html
ab
今日推荐