用Java实现一个必定会产生死锁的程序

时间:2021-08-08 20:50:27
public class TestLock {
public static void main(String[] args) {
Thread t1 = new Thread(new deadLock(false));
Thread t2 = new Thread(new deadLock(true));
t1.start();
t2.start();
}
}
class deadLock implements Runnable{
boolean flage;
deadLock(boolean flage){
this.flage=flage;
}
Object obj1=new Object();
Object obj2=new Object();


public void run() {
if(this.flage){
synchronized (obj1) {
System.out.println(Thread.currentThread().getName()+"hava o1");
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
synchronized (obj2) {
System.out.println(Thread.currentThread().getName()+"hava o2");
}
}
}else{
synchronized (obj2) {
System.out.println(Thread.currentThread().getName()+"hava o2");
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
synchronized (obj1) {
System.out.println(Thread.currentThread().getName()+"hava o1");
}
}
}

}

}


用Java实现一个必定会产生死锁的程序