首先建立自己的所对象,因为查看死锁现象所以得有两个以上的锁对象.
public class MyLock {
public static final Object objA = new Object();
public static final Object objB = new Object();
}
然后写死锁类
public class DieLock extends Thread{
private boolean flag;
public DieLock(boolean flag){
this.flag = flag;
}
@Override
public void run() {
if(flag){
synchronized(MyLock.objA){
System.out.println("true----------------objA");
synchronized(MyLock.objB){
System.out.println("true--------------objB");
}
}
}else{
synchronized(MyLock.objB){
System.out.println("false------------------objB");
synchronized(MyLock.objA){
System.out.println("false-----------------objA");
}
}
}
}
}
随后启动线程的测试类
public class Test {
public static void main(String[] args) {
DieLock d1 = new DieLock(true);
DieLock d2 = new DieLock(false);
d1.start();
d2.start();
}
}