Java之死锁两种方式模拟

 锁顺序死锁

package ReadWirteLock;

public class TestDeadLock {
	
	private final Object left = new Object();
	private final Object right = new Object();
	
	
	public void leftRight() {
		synchronized (left) {
			synchronized (right) {
				System.out.println("left right");
			}
		}
		
	}
	
	public void rightLeft() {
		synchronized (right) {
			synchronized (left) {
				System.out.println(" ---------------");
			}
		}
	}
	
	
	public static void main(String[] args) {
		TestDeadLock deadLock =new TestDeadLock();
		Thread thread =new Thread(() -> {
			for(int i=0;i<1000;i++) {
				deadLock.leftRight();
			}
		});
		Thread thread2 =new Thread(() -> {
			for(int i=0;i<1000;i++) {
				deadLock.rightLeft();
			}
		});
		
		thread.start();
		thread2.start();
	}

}

动态顺序死锁 

猜你喜欢

转载自blog.csdn.net/qq_24532581/article/details/86650035