public class DeadLock implements Runnable {
//为什么用static object?因为不使用static,那么deadLock1,deadLock2都会有自己的私有变量,也就是说每个线程取得互斥锁时,会访问属于自己的object1,object2,但是如果两个对象共享object,每个线程就会争抢object
private static Object object1=new Object();
private static Object object2=new Object();
private int flag;
public void run() {
System.out.println(Thread.currentThread().getName()+" flag:"+flag);
if(1==flag){
synchronized (object1) {//当前线程不释放object1这个锁的同时,需要object2的锁,但是object2的锁,被其他线程占用,其他线程想要object1的锁
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
synchronized (object2){
System.out.println(0);
}
}
}
if(0==flag){
synchronized (object2) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
synchronized (object1){
System.out.println(1);
}
}
}
}
public static void main(String[] args) {
DeadLock deadLock1 = new DeadLock();
DeadLock deadLock2 = new DeadLock();
deadLock1.flag=1;
deadLock2.flag=0;
Thread thread1 = new Thread(deadLock1);
Thread thread2 = new Thread(deadLock2);
thread1.setName("thread1");
thread2.setName("thread2");
thread1.start();
thread2.start();
}
}