本帖最后由 forTomorrow 于 2015-6-5 15:03 编辑
代码:
package com.itheima;
public class DeadLock implements Runnable {
private boolean flag;// 用于区分两个不同的线程
public DeadLock(boolean flag) {
this.flag = flag;
}
public void run() {
if (flag) {
while (true) {
synchronized (Lock.locka) {
System.out.println("if---locka");
synchronized (Lock.lockb) {// 持有b锁才可以继续执行下面的程序
System.out.println("if---lockb");
}
}
}
} else {
while (true) {
synchronized (Lock.lockb) {
System.out.println("else---lockb");
synchronized (Lock.locka) {// 持有a锁才可以继续执行下面的程序
System.out.println("else---locka");
}
}
}
}
}
static class Lock {// 定义两个锁对象
static Object locka = new Object();
static Object lockb = new Object();
}
public static void main(String[] args) {
new Thread(new DeadLock(true)).start();
new Thread(new DeadLock(false)).start();
}
}
运行结果一:
if---locka
if---lockb
if---locka
if---lockb
if---locka
if---lockb
if---locka
if---lockb
if---locka
else---lockb
运行结果二:
if---locka
else---lockb
运行结果三:
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
else---locka
else---lockb
if---locka
运行结果四:
不帖运行结果了,因为很长,是另外一种情况,两个线程都循环完至少一次,最后某个时候达到死锁,阻塞
|
|