必然死锁——模拟两个人转账
使用syn锁对from和to进行资源的加锁。如果转账者和被转账的人都获取了相应的锁而不释放,则会造成必然的死锁。
package deadlock; /** * @author leon * @描述 转账时候遇到死锁,一旦打开注释。便会发生死锁。 */ public class TransferMoney implements Runnable{ int flag = 1; static Account a = new Account(500); static Account b = new Account(500); public static void main(String[] args) throws InterruptedException { TransferMoney r1 = new TransferMoney(); TransferMoney r2 = new TransferMoney(); r1.flag = 1; r2.flag = 0; Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); t1.join();
t2.join(); System.out.println("a的余额" + a.balance + "元"); System.out.println("b的余额" + b.balance + "元"); } @Override public void run() { if (flag == 1) { transferMoney(a, b, 200); } if (flag == 0) { transferMoney(b, a, 200); } } public static void transferMoney(Account from, Account to, int amount) { synchronized (from) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (to) { if (from.balance - amount < 0) { System.out.println("余额不足,转账失败"); } from.balance -= amount; to.balance += amount; System.out.println("转账成功," + amount +"元"); } } } static class Account { public Account(int balance) { this.balance = balance; } int balance; } }
通过使用jps和jstack命令查到: