public class DeadLock implements Runnable {
private boolean flag;
private static final Object o1 = new Object();
private static final Object o2 = new Object();
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ":flag=" + flag);
if (flag == true) {
synchronized (o1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadName + "进入同步为o1准备进入日o2");
/*会造成死锁
synchronized (o2) {
System.out.println(threadName + "已经进入同步块o2");
}*/
//解决死锁
// synchronized (o2) {
System.out.println(threadName+"已经进入同步块o2");
// }
}
}
if (flag == false) {
synchronized (o2) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadName + "进入同步为o2准备进入日o1");
synchronized (o1) {
System.out.println(threadName + "已经进入同步块o1");
}
}
}
}
public static void main(String[] args) {
DeadLock d1 = new DeadLock();
DeadLock d2 = new DeadLock();
d1.flag = true;
d2.flag = false;
new Thread(d1).start();
new Thread(d2).start();
}
}
当在线程同步锁中当一个对象还没有释放,另一个同步锁无法得到资源(使用的资源顺序相反),则会造成死锁.
解决1:如代码所述,取消一个同步锁
解决2:不用取消,但使用的的资源顺序要一致。