其他分享
首页 > 其他分享> > 模拟一个死锁

模拟一个死锁

作者:互联网

场景描述

1.有两个对象锁A1、A2

2.两个线程t1、t2

3.t1的执行顺序是A1-->A2, t2的执行顺序是A2-->A1

4.出现状态 t1持有 A1 锁,等待 A2 锁; t2 持有 A2 锁,等待 A1 锁

5.出现死锁

检查死锁方法:使用jps查看线程pid,用jstack pid查看线程运行情况

代码演示

DeadLock

package com.dwz.concurrency.chapter8;

public class DeadLock {
    private OtherService otherService;
    private final Object LOCK = new Object();

    public DeadLock(OtherService otherService) {
        this.otherService = otherService;
    }
    
    public void m1() {
        synchronized(LOCK) {
            System.out.println("m1--" + Thread.currentThread());
            otherService.s1();
        }
    }
    
    public void m2() {
        synchronized(LOCK) {
            System.out.println("m2--" + Thread.currentThread());
        }
    }
    
}

OtherService

package com.dwz.concurrency.chapter8;

public class OtherService {
    private DeadLock deadLock;
    private final Object LOCK = new Object();
    
    public void setDeadLock(DeadLock deadLock) {
        this.deadLock = deadLock;
    }
    
    public void s1() {
        synchronized (LOCK) {
            System.out.println("s1========" + Thread.currentThread());
        }
    }
    
    public void s2() {
        synchronized (LOCK) {
            System.out.println("s2========" + Thread.currentThread());
            deadLock.m2();
        }
    }
}
    

测试类

package com.dwz.concurrency.chapter8;

public class DeadLockTest {

    public static void main(String[] args) {
        OtherService otherService = new OtherService();
        DeadLock deadLock = new DeadLock(otherService);
        otherService.setDeadLock(deadLock);
        
        new Thread() {
            @Override
            public void run() {
                while(true) {
                    deadLock.m1();
                }
            }
        }.start();
        
        new Thread() {
            @Override
            public void run() {
                while(true) {
                    otherService.s2();
                }
            }
        }.start();
    }

}

结果:没有异常信息,程序阻塞

标签:DeadLock,一个,void,死锁,new,deadLock,public,模拟,otherService
来源: https://www.cnblogs.com/zheaven/p/12059807.html