如何避免死锁,有序的上锁,有序的开锁
/**
* @author Levin
* @version 1.0.0
* @Title Threads
* @Description TODO
* @Date 2019/6/10 19:15
*/
public class Threads implements Runnable {
private Object a, b;
public Threads(Object a, Object b) {
this.a = a;
this.b = b;
}
@Override
public void run() {
synchronized (a) {
System.out.println(Thread.currentThread().getName() + " lock:" + a);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (b) {
System.out.println(Thread.currentThread().getName() + " lock:" + b);
}
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
Object o1 = new Object();
Object o2 = new Object();
Threads t1 = new Threads(o1, o2);
Threads t2 = new Threads(o2, o1);
new Thread(t1).start();
new Thread(t2).start();
}
}