/**
* @author JZWen
* @date 2019年2月24日
*/
/**
* @author JZWen
*
*/
public class DeathLock {
/**
* @param args
*/
public static void run() {
MyThread mThread = new MyThread(true);
new Thread(mThread, "jzw").start();
new Thread(mThread , "cjj").start();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
run();
}
}
class MyThread implements Runnable{
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
Object o1 = new Object();
Object o2 = new Object();
boolean sign = true;
/**
* 2019-02-24 15:32:47
* 构造函数
*/
public MyThread(boolean sign) {
// TODO Auto-generated constructor stub
this.sign = sign;
}
@Override
public void run() {
// TODO Auto-generated method stub
/**
* 重点
*/
if(sign) {
sign = false;
//获取o1锁
synchronized (o1) {
//然后我们sleep,然后在打印线程名
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("当前线程名:"+Thread.currentThread().getName());
//之后我们在没有释放o1锁的情况下,去获取o2锁。
synchronized (o2) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("当前线程名:"+Thread.currentThread().getName());
}
}
}
if(!sign) {
sign = true;
//获取o1锁
synchronized (o2) {
//然后我们sleep,然后在打印线程名
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("当前线程名:"+Thread.currentThread().getName());
//之后我们在没有释放o1锁的情况下,去获取o2锁。
synchronized (o1) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("当前线程名:"+Thread.currentThread().getName());
}
}
}
}
}