日期:2014-05-20 浏览次数:20861 次
public void run() {
System.out.println("flag = " + flag);
if(flag == 1) {
synchronized(o1) {
try {
Thread.sleep(100);
} catch(InterruptedException e) {
System.out.println("Thread.sleep()出错了。");
e.printStackTrace();
}
synchronized(o2) {
System.out.println("1111111");
}
}
}
if(flag == 0) {
synchronized(o2) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Thread.sleep()出错了。");
e.printStackTrace();
}
synchronized(o1) {
System.out.println("0000000");
}
}
}
}
public class TestDeadLock implements Runnable {
public int flag = 1;
static Object o1 = new Object();
static Object o2 = new Object();
public void run() {
System.out.println("flag = " + flag);
if (flag == 1) {
synchronized (o1) {
//t1锁住了o1
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("Thread.sleep()出错了。");
e.printStackTrace();
}
//t1尝试锁o2 ,可o2 已经被t2 给锁住了还没释放,一直等待
synchronized (o2) {
System.out.println("1111111");
}
}
//到了这里才会释放o1的锁
}
if (flag == 0) {
synchronized (o2) {
//t2锁住了o2
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread.sleep()出错了。");
e.printStackTrace();
}
//t2尝试锁o1,可t1锁住了o1 而且要等待t2释放o2后才能释放o1,就发生死锁了