其他分享
首页 > 其他分享> > 多线程死锁案例以及查看方法

多线程死锁案例以及查看方法

作者:互联网

多线程死锁案例以及查看方法

我们先定义一个类调用DeadLockOtherService

public class DeadLockTest {
    public static void main(String[] args) {
        DeadLock deadLock = new DeadLock();
        OtherService otherService = new OtherService();
        deadLock.setOtherService(otherService);
        otherService.setDeadLock(deadLock);

        new Thread(() -> {
            while (true) {
                deadLock.m1();
            }
        }, "T1").start();
        new Thread(() -> {
            while (true) {
                otherService.s2();
            }
        }, "T2").start();
    }
}
public class DeadLock {
    private OtherService otherService;

    public void setOtherService(OtherService otherService) {
        this.otherService = otherService;
    }

    // DeadLock的实例的锁-资源A
    private final Object LOCK = new Object();

    public void m1() {
        synchronized (LOCK) {
            System.out.println("********m1********");
            otherService.s1();
        }
    }

    public void m2() {
        synchronized (LOCK) {
            System.out.println("********m2********");
        }
    }
}

public class OtherService {
    private DeadLock deadLock;

    public void setDeadLock(DeadLock deadLock) {
        this.deadLock = deadLock;
    }

    // OtherService的实例的锁-资源B
    private final Object LOCK = new Object();

    public void s1() {
        synchronized (LOCK) {
            System.out.println("========s1========");
        }
    }

    public void s2() {
        synchronized (LOCK) {
            System.out.println("========s2========");
            deadLock.m2();
        }
    }

}

可以看到:

线程一调用DeadLockm1方法,m1使用了DeadLockLOCK锁,m1调用了OtherServices1,s1使用了DeadLockLOCK锁,线程二调用OtherServices2,而s2调用了DeadLockm2,而m2使用的DeadLock的LOCK被m1抢占着,所以就形成了死锁。

接下来使用jpsjstack命令来看一下:

标签:DeadLock,LOCK,deadLock,案例,死锁,OtherService,多线程,public,otherService
来源: https://www.cnblogs.com/stormsquirrel/p/13622121.html