死锁
死锁就好比伊邪那美,轮回吧!!!!
解除轮回,就跳出了死锁。
public class Test{
public static void main(String[] args) {
DeadLockRunnable d1 = new DeadLockRunnable();
d1.flag = 1;
DeadLockRunnable d2 = new DeadLockRunnable();
d2.flag = 2;
new Thread(d1,"张三").start();
//常用线程休眠来有效的解决死锁问题,释放下面代码,则能解决本例死锁问题。
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
new Thread(d2,"李四").start();
}
}
class DeadLockRunnable implements Runnable{
public int flag;
private static Object o1 = new Object();
private static Object o2 = new Object();
@Override
public void run() {
// TODO Auto-generated method stub
if(flag ==1) {
System.out.println(Thread.currentThread().getName() + "获取了资源o1,等待获取资源o2");
synchronized(o1){
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(o2) {
System.out.println(Thread.currentThread().getName() + "执行完毕");
}
}
}
if(flag ==2) {
System.out.println(Thread.currentThread().getName() + "获取了资源o2,等待获取资源o1");
synchronized(o2){
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(o1) {
System.out.println(Thread.currentThread().getName() + "执行完毕");
}
}
}
}
}