手把手教你写一个死锁

本文介绍了死锁和活锁的概念,详细分析了死锁发生的四个必要条件,并通过一个转账代码实例展示了死锁的产生过程。同时,提出了破坏死锁条件的三种解决方法,包括一次性申请所有资源、资源抢占和按序申请资源。最后提供了两种具体的解决方案。
摘要由CSDN通过智能技术生成

之前看到一个小伙伴分享的面试题,笔试阶段让写一个死锁,有点意思。

什么是死锁、活锁?

学过多线程,大家多锁应该不陌生
死锁: 一组互相竞争资源的线程因互相等待,导致“永久”阻塞的现象。
活锁: 活锁指的是任务或者执行者没有被阻塞,由于某些条件没有满足,导致一直重复“”尝试—失败—尝试—失败“”的过程。处于活锁的实体是在不断的改变状态,活锁有可能解开继续往下运行。

死锁发生的条件?

这四个条件同时满足,就会产生死锁。
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
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值