多线程死锁

多线程死锁发生的原因

死锁怎么发生的呢?
死锁大致的原因就是锁A中套了个锁B,锁B中又套了个锁A,两个锁都在那边等着对方释放锁,所以造成了死锁的原因。
下面例子就是A中有B,B中有A

package com.lilei;

public class TestDeadLock {
    public static void main(String[] args) {
        DeadLock dead = new DeadLock();
        MyThread t1 = new MyThread(dead, 1, 2);
        MyThread t2 = new MyThread(dead, 3, 4);
        MyThread t3 = new MyThread(dead, 5, 6);
        MyThread t4 = new MyThread(dead, 7, 8);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
class MyThread extends Thread{
    private DeadLock dl;
    private int a;
    private int b;
    public MyThread(DeadLock dl,int a,int b) {
        this.dl = dl;
        this.a = a;
        this.b = b;
    }
    @Override
    public void run() {
        dl.read();
        dl.write(a, b);
    }

}
class DeadLock{
    /**
     * 静态内部类
     * @author lilei
     *
     */
    private static class Resource{
        public int value;
    }
    private Resource resourceA = new Resource();
    private Resource resourceB = new Resource();
    public int read(){
        synchronized (resourceA) {
            System.out.println("read():"+Thread.currentThread().getName()+"获取了A的锁");
            synchronized (resourceB) {
                System.out.println("read():"+Thread.currentThread().getName()+"获取了B的锁");
                return resourceA.value+resourceB.value;
            }
        }
    }
    public void write(int a,int b){
        synchronized (resourceB) {
            System.out.println("read():"+Thread.currentThread().getName()+"获取了B的锁");
            synchronized (resourceA) {
                System.out.println("read():"+Thread.currentThread().getName()+"获取了A的锁");
                resourceA.value = a;
                resourceB.value = b;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值