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

死锁检查和查看

程序员文章站 2022-05-22 11:21:27
...

用户A转账给用户B,用户B转账给用户A

public class Account {
    private Integer balance = 200;

    private void transfer(Account target, int amount){
        synchronized (this){
            synchronized (target){
                if(this.balance >= amount){
                    this.balance -= amount;
                    target.balance += amount;
                }
            }
        }
    }

    public static void main(String[] args){

        for(int i = 0 ; i < 100000 ; i++ ) {
            Account account1 = new Account();
            Account account2 = new Account();
            Account account3 = new Account();
            Account account4 = new Account();

            Thread th1 = new Thread(() -> {
                account1.transfer(account2, 100);
            });
            Thread th2 = new Thread(() -> {
                account2.transfer(account1, 100);
            });

            th1.start();
            th2.start();
            try {
                th1.join();
                th2.join();
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.println(i);

        }

    }
}

重复试验直到有死锁现象出现,运用jconsole工具查看死锁

死锁检查和查看

本地进程 -> 连接

死锁检查和查看

线程 -> 检查死锁 :两个线程分别占有对方所需要的锁,形成死锁

死锁检查和查看

相关标签: 死锁