import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class LeftRightDeadLockThread {
private Object left = new Object();
private Object right = new Object();
public void leftRight() {
synchronized (left) {
synchronized (right) {
System.out.println("leftRight");
}
}
}
public void rightLeft() {
synchronized (right) {
synchronized (left) {
System.out.println("rightLeft");
}
}
}
/*
* A- 锁住 left- 尝试锁住 right-- 永远等待
* B- 锁住 right- 尝试锁住 left-- 永远等待
*/
public static void main(String[] args) {
final LeftRightDeadLockThread lRDLT = new LeftRightDeadLockThread();
ExecutorService service = Executors.newFixedThreadPool(2);
service.submit(new Runnable() {
@Override
public void run() {
while (true) {
lRDLT.leftRight();
}
}
});
service.submit(new Runnable() {
@Override
public void run() {
while (true) {
lRDLT.rightLeft();
}
}
});
service.shutdown();
}
}