/**
* 死锁
*当第一个线程进入第一个if进入锁定o1锁定o2的同步块,第二个线程在外边等待
*当第一个线程出来进入第二个if,第二个线程进第一个if进入o1同步代码块,
*第一个线程进入第二个if的o2同步代码块,两个线程互相等待彼此释放锁,造成死锁
*/
public class DiedLock implements Runnable{
boolean flag ;
Object o1 = new Object();
Object o2 = new Object();
public static void main(String[] args) {
DiedLock dl = new DiedLock();
Thread t1 = new Thread(dl);
t1.start();
Thread t2 = new Thread(dl);
t2.start();
}
@Override
public void run() {
if(!flag) {
synchronized(o1) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(o2) {
flag = true;
System.out.println("hello");
}
}
}
if(flag) {
synchronized(o2) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(o1) {
flag = false;
System.out.println("hi");
}
}
}
}
}
* 死锁
*当第一个线程进入第一个if进入锁定o1锁定o2的同步块,第二个线程在外边等待
*当第一个线程出来进入第二个if,第二个线程进第一个if进入o1同步代码块,
*第一个线程进入第二个if的o2同步代码块,两个线程互相等待彼此释放锁,造成死锁
*/
public class DiedLock implements Runnable{
boolean flag ;
Object o1 = new Object();
Object o2 = new Object();
public static void main(String[] args) {
DiedLock dl = new DiedLock();
Thread t1 = new Thread(dl);
t1.start();
Thread t2 = new Thread(dl);
t2.start();
}
@Override
public void run() {
if(!flag) {
synchronized(o1) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(o2) {
flag = true;
System.out.println("hello");
}
}
}
if(flag) {
synchronized(o2) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(o1) {
flag = false;
System.out.println("hi");
}
}
}
}
}