/**
* 一个简单的死锁类
* @author iStar
* 当类的对象为T1,先锁定O1,睡眠500毫秒,然后锁定O2;
* 而T1在睡眠的时候另一个对象T2线程启动,先锁定O2,睡眠500毫秒,等待T1释放O1;
* T1睡眠结束后需要锁定O2才能继续执行,而此时O2已被T2锁定;
* T2睡眠结束后需要锁定O1才能继续执行,而此时O1已被T1锁定;
* T1、T2相互等待,都需要对方锁定的资源才能继续执行,从而死锁。
*/
class LockThread implements Runnable {
Object o1 = new Object();
Object o2 = new Object();
@Override
public void run() {
if (Thread.currentThread().getName().equals("t1")) {
synchronized (o1) {
System.out.println(Thread.currentThread().getName() + "对o1加锁");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (o2) {
System.out.println(Thread.currentThread().getName()
+ "对o2加锁");
}
}
} else {
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + "对o2加锁");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (o1) {
System.out.println(Thread.currentThread().getName()
+ "对o1加锁");
}
}
}
}
}
public class DeadLockDemo {
public static void main(String[] args) {
LockThread st = new LockThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
原文:http://www.cnblogs.com/123Aizhen-li/p/5255093.html