public class TestDeadLock implements Runnable{
public int flag = 0;
public static Object o1 =new Object();
public static Object o2 = new Object();
public static void main(String[] args) {
TestDeadLock t = new TestDeadLock();
TestDeadLock tt = new TestDeadLock();
t.flag = 0;
tt.flag = 1;
Thread t1 = new Thread(t);
Thread t2 = new Thread(tt);
t1.start();
t2.start();
}
public void run() {
System.out.println("flag ="+ flag);
if (flag == 1) {
synchronized(o1){
try {
Thread.sleep(1000);
}catch(InterruptedException e) {
System.out.println("fail!");
}
}
synchronized(o2) {
System.out.println("thread1 is close!");
}
} else {
synchronized(o2){
try{
Thread.sleep(5000);
}catch(InterruptedException e) {
System.out.println("fail!");
}
}
synchronized(o1) {
System.out.println("thread2 is close!");
}
}
}
}
public class TestDeadLock implements Runnable{
public int flag = 0;
public static Object o1 =new Object();
public static Object o2 = new Object();
public static void main(String[] args) {
TestDeadLock t = new TestDeadLock();
TestDeadLock tt = new TestDeadLock();
t.flag = 0;
tt.flag = 1;
Thread t1 = new Thread(t);
Thread t2 = new Thread(tt);
t1.start();
t2.start();
}
public void run() {
System.out.println("flag ="+ flag);
if (flag == 1) {
synchronized(o1){
try {
Thread.sleep(1000);
}catch(InterruptedException e) {
System.out.println("fail!");
}
synchronized(o2) {//在锁定o1结束的时候有一小段空余时间导致失败,所以要把锁定o2也要放在锁定o1的代码段里
System.out.println("thread1 is close!");
}
}
} else {
synchronized(o2){
try{
Thread.sleep(5000);
}catch(InterruptedException e) {
System.out.println("fail!");
}
synchronized(o1) {//同上
System.out.println("thread2 is close!");
}
}
}
}
}