java编写死锁代码

public class T5 {
	class MyLock {
		// 创建两把锁对象
		public Object objA = new Object();
		public Object objB = new Object();

	}

	class DemoThread extends Thread {

		private boolean flag;
		private MyLock myLock;

		public DemoThread(Boolean flag, MyLock myLock) {
			this.flag = flag;
			this.myLock = myLock;
		}

		@Override
		public void run() {
			if (flag) {
				synchronized (myLock.objA) {
					System.out.println("if A");
					synchronized (myLock.objB) {
						System.out.println("if B");
					}
				}
			} else {
				synchronized (myLock.objB) {
					System.out.println("else B");
					synchronized (myLock.objA) {
						System.out.println("else A");
					}
				}
			}
		}
	}

	public static void main(String[] args) {
		T5 t5 = new T5();
		MyLock myLock = t5.new MyLock();
		DemoThread dl1 = t5.new DemoThread(true,myLock);
        DemoThread dl2 = t5.new DemoThread(false,myLock);
        dl1.start();
        dl2.start();

	}

}

    原文作者:java锁
    原文地址: https://blog.csdn.net/lirenzuo/article/details/72830090
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞