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

一、概述

  • 甲有两个儿子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也一直在等待。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值