package 死锁demo;
public class DeadLock implements Runnable{
boolean lockFormer;
static Object o1 = new Object();
static Object o2 = new Object();
DeadLock(boolean loackFormer){
this.lockFormer = loackFormer;
}
@Override
public void run() {
if(this.lockFormer) {
synchronized(o1) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(o2) {
System.out.println("1ok");
}
}
}else {
synchronized(o2) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(o1) {
System.out.println("2ok");
}
}
}
}
}
package 死锁demo;
public class TestThread {
public static void main(String[] args){
Thread t1 = new Thread(new DeadLock(true));
Thread t2 = new Thread(new DeadLock(false));
t1.start();
t2.start();
}
}
这里运用synchronized和sleep方法产生了死锁。因为sleep方法和wait方法不同,sleep方法不会释放内存锁,所以因为synchronized的存在导致产生了死锁,无运行结果的产生。
这是我看网上一个大牛写的,我觉得写的很好简单易懂,故此分享。