之前看到一个小伙伴分享的面试题,笔试阶段让写一个死锁,有点意思。
什么是死锁、活锁?
学过多线程,大家多锁应该不陌生
死锁: 一组互相竞争资源的线程因互相等待,导致“永久”阻塞的现象。
活锁: 活锁指的是任务或者执行者没有被阻塞,由于某些条件没有满足,导致一直重复“”尝试—失败—尝试—失败“”的过程。处于活锁的实体是在不断的改变状态,活锁有可能解开继续往下运行。
死锁发生的条件?
这四个条件同时满足,就会产生死锁。
1.互斥,共享资源 X 和 Y 只能被一个线程占用;
2.占有且等待,线程 T1 已经取得共享资源 X,在等待共享资源 Y 的时候,不释放共享资源 X;
3.不可抢占,其他线程不能强行抢占线程 T1 占有的资源;
4.循环等待,线程 T1 等待线程 T2 占有的资源,线程 T2 等待线程 T1 占有的资源,就是循环等待。
我们通过下面一段互相转账代码演示:
定义账户信息实体类
public class Account {
private String accountName;
private int balance;
public Account(String accountName, int balance) {
this.accountName = accountName;
this.balance = balance;
}
//更新转出方的余额
public void debit(int amount){
this.balance-=amount;
}
//更新转入方的余额
public void credit(int amount){
this.balance+=amount;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
}
定义转账线程代码
public class TransferAccount implements Runnable{
private Account fromAccount; //转出账户
private Account toAccount; //转入账户
private int amount;
Allocator allocator;
public TransferAccount(Account fromAccount, Account toAccount, int amount) {
this.fromAccount = fromAccount;
this.toAccount = toAccount;
this.amount = amount;
this.allocator=allocator;
}
@Override
public void run() {
while(true){
synchronized (fromAccount) {
// 1
synchronized (toAccount) {
// 2
if (fromAccount.getBalance() >= amount) {
fromAccount