死锁检查和查看
程序员文章站
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工具查看死锁
本地进程 -> 连接
线程 -> 检查死锁 :两个线程分别占有对方所需要的锁,形成死锁
上一篇: 在OpenCV里实现棋盘生成
下一篇: Mysql数据库是否发生死锁?死锁的场景