欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

高并发编程:8、多线程死锁分析

程序员文章站 2022-04-17 14:39:41
...

一、概述

  • 甲有两个儿子A和B,乙有两个儿子C和D。
  • 甲有一把锁钥匙在A儿子身上,乙有一把锁钥匙在C儿子身上。
  • A认识D,需要找D帮忙拿一下东西,但是D没有钥匙,钥匙在大哥C身上,等待大哥C办完事才能拿到钥匙。
  • C认识B,需要找B帮忙拿一下东西,但B没有钥匙,钥匙在大哥A身上,等待大哥A办完事才能拿到钥匙。
  • 这样就产生了大家都在等待对方大哥办完事情,但是这事情永远不能完成,这就叫死锁。

二、代码

package com.cfl.thread;

/**
 * 多线程死锁分析,案列介绍
 * @author chenfenli
 *
 */
public class Thread9 {
    public static void main(String[] args) throws Exception {
	final DeadLock deadLock = new DeadLock();
	final OtherServer otherServer = new OtherServer(deadLock);
	deadLock.setOtherServer(otherServer);
	
	new Thread(new Runnable() {
	    public void run() {
		while (true) {
		    deadLock.d1();
		}
	    }
	},"甲").start();
	new Thread(new Runnable() {
	    public void run() {
		while (true) {
		    otherServer.s2();
		}
	    }
	},"乙").start();
    }
    static class DeadLock {	
	private static Object LOCK =  new Object();	
	private OtherServer otherServer;
	public void d1() {
	    System.out.println("A ================== start");
	    synchronized(LOCK) {
		System.out.println("A ================== synchronized");
		otherServer.s1();
		System.out.println("A ================== end");
		}
	    }
	    public void d2() {
		System.out.println("B ================== start");
		synchronized(LOCK) {
		System.out.println("B ================== synchronized");
	    }
        }
	public OtherServer getOtherServer() {
	    return otherServer;
	}
	public void setOtherServer(OtherServer otherServer) {
	    this.otherServer = otherServer;
	}
    }
    static class OtherServer {	
	private final Object LOCK =  new Object();
	private DeadLock deadLock;	
	public OtherServer(DeadLock deadLock) {
	    this.deadLock = deadLock;
	}	
	public void s1() {
	    System.out.println("C ================== start");
	    synchronized(LOCK) {
		System.out.println("C ================== synchronized");
	    }
	}
	public void s2() {
	    System.out.println("D ================== start");
	    synchronized (LOCK) {
	        System.out.println("D ================== synchronized");
		deadLock.d2();
		System.out.println("D ================== end");
	    }
        }
    }
}
.....
D ================== end
A ================== end
A ================== start
A ================== wait...
D ================== start
C ================== start
D ================== end
A ================== end
A ================== start
A ================== wait...
D ================== start
C ================== wait...
B ================== start
  • 可以看到随后死锁了,A一直在等待,C也一直在等待。