多线程死锁示例

class Test implements Runnable{
private boolean flag;
Test(boolean flag){
this.flag = flag;
}
public void run(){
if(flag){
synchronized(MyLock.lockA){
System.out.println("if lockA");
synchronized(MyLock.lockB){
System.out.println("if lockB");
}
}
}else{
synchronized(MyLock.lockB){
System.out.println("else lockB");
synchronized(MyLock.lockA){
System.out.println("else lockA");
}
}
}
}
}

class MyLock{
public static final MyLock lockA= new MyLock();
public static final MyLock lockB = new MyLock();
}

class DemoLockTest{

public static void main(String[] arg){

Test a = new Test(true);
Test b = new Test(false);

Thread t1 = new Thread(a);
Thread t2 = new Thread(b);

t1.start();
t2.start();

}

}

posted @ 2018-07-04 22:05  仙人掌的成长  阅读(119)  评论(0编辑  收藏  举报