java中互锁代码测试

class TestDeadLock implements Runnable {

	private int flag;
	private int cnt = 0;
	private static Object obj1 = new Object(); //需要static,不然下面new TestDeadLock就会出现多个对象
	private static Object obj2 = new Object(); //导致访问的是非同一把锁而相互间没有了互锁关系

	public static void mainTest(String[] args) {
		TestDeadLock dl1 = new TestDeadLock();
		TestDeadLock dl2 = new TestDeadLock();
		dl1.flag = 1;
		dl2.flag = 2;

		Thread t1 = new Thread(dl1);
		Thread t2 = new Thread(dl2);

		t1.start();
		t2.start();
		System.out.println("start");
	}

	public void run() {
		for(int i=0; i<100; i++){
			if (flag == 1) {
				System.out.println("flag1 --- request obj1");
				synchronized (obj1) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException ie) {
						ie.printStackTrace();
					}
					System.out.println("flag1,obj1, cnt="+cnt);
					cnt++;
					if(cnt > 6){
						System.out.println("flag1 === request obj2");
						synchronized (obj2) {
							System.out.println("flag1,obj2");
						}
					}
				}
			}
	
			if (flag == 2) {
				System.out.println("flag2 --- request obj2");
				synchronized (obj2) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException ie) {
						ie.printStackTrace();
					}
					System.out.println("flag2,obj2, cnt="+cnt);
					cnt++;
					if(cnt > 3){
						System.out.println("flag2 === request obj1");
						synchronized (obj1) {
							System.out.println("flag2,obj1");
						}
					}
				}
			}
		}
	}
}

结果:

start
flag1 --- request obj1
flag2 --- request obj2
flag1,obj1, cnt=0
flag1 --- request obj1
flag2,obj2, cnt=0
flag2 --- request obj2
flag2,obj2, cnt=1
flag2 --- request obj2
flag1,obj1, cnt=1
flag1 --- request obj1
flag1,obj1, cnt=2
flag1 --- request obj1
flag2,obj2, cnt=2
flag2 --- request obj2
flag1,obj1, cnt=3
flag1 --- request obj1
flag2,obj2, cnt=3
flag2 === request obj1
flag1,obj1, cnt=4
flag1 --- request obj1
flag2,obj1
flag2 --- request obj2
flag2,obj2, cnt=4
flag2 === request obj1
flag1,obj1, cnt=5
flag1 --- request obj1
flag2,obj1
flag2 --- request obj2
flag1,obj1, cnt=6
flag2,obj2, cnt=5
flag2 === request obj1
flag1 === request obj2

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