写一个程序演示死锁
编程中,我们要极力避免死锁的出现;但,为了理解死锁的形成,特写该程序进行模拟;
建议参考:死锁产生的原因和解锁的方法
package cn.mike.demo;
/**
* @author Administrator
* @usage 演示一下死锁是怎么形成的
*/
public class DeadLockDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new DeadLockThread(true));
Thread t2 = new Thread(new DeadLockThread(false));
t1.start();
t2.start();
}// end method-main
}// end class-DeadLockDemo
class MyLock {
static Object lockA = new Object();
static Object lockB = new Object();
}
class DeadLockThread implements Runnable {
boolean flag = false;
DeadLockThread(boolean f) {
flag = f;
}
public void run() {
if (flag) {
synchronized (MyLock.lockA) {
System.out.println("if---MyLock.lockA");
synchronized (MyLock.lockB) {
System.out.println("if---MyLock.lockB");
}
}
} // end if-conditon
else {
synchronized (MyLock.lockB) {
System.out.println("else---MyLock.lockB");
synchronized (MyLock.lockA) {
System.out.println("else---MyLock.lockA");
}
}
} // end else-condition
}// end method-run
}// end class-Test