public class DeadLock implements Runnable {
Object o1 = new Object();
Object o2 = new Object();
int flag = 0;
public DeadLock(int flag) {
this.flag = flag;
}
public static void main(String[] args) {
DeadLock deadLock = new DeadLock(0);
deadLock.flag = 0;
Thread threadA = new Thread(deadLock);
deadLock.flag = 1;
Thread threadB = new Thread(deadLock);
threadA.start();
threadB.start();
}
@Override
public void run() {
System.out.println(flag);
if (flag == 0) {
synchronized (o1) {
System.out.println("I have got O1,then I will get o2");
synchronized (o2) {
System.out.println("i have get o2");
}
}
}
if (flag == 1) {
synchronized (o2) {
System.out.println("I have got O2,then I will get o1");
synchronized (o1) {
System.out.println("i have get o1");
}
}
}
}
}