等待/通知机制

等待/通知

在之前的破坏占有且等待条件来解决死锁问题时,我们使用了while(!getAllAccount(account1, account2)) { }来循环等待能够获取到全部所需资源。在并发量大的情况下,这种行为会严重消耗CPU。我们可以用等待/通知机制来进行优化,当资源不足时,进行等待,资源充足时再被唤醒。

Java内置的synchronized配合wait()、notify()、notifyAll()就可以实现等待/通知机制。调用wait()方法使当前线程等待,调用notify()、notifyAll()来唤醒等待的线程。下面通过代码来看一下等待/通知机制的使用。

Account.java

package com.zcyt085.synchronizedtest.demo6;

/**
 * @author tu
 */
public class Account {
    private int money;

    public Account(int money) {
        this.money = money;
    }

    public synchronized void addMoney(int num) {
        money += num;
    }


    public synchronized boolean subMoney(int num) {
        if(money >= num) {
            money -= num;
            return true;
        }
        return false;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

}

MyThread.java

package com.zcyt085.synchronizedtest.demo6;

import java.util.ArrayList;

/**
 * @author tu
 */
public class MyThread extends Thread {
    private final Account account1;
    private final Account account2;
    private final int num;
    private final ArrayList<Account> arrayList;

    public MyThread(Account account1, Account account2, int num, ArrayList<Account> arrayList) {
        this.account1 = account1;
        this.account2 = account2;
        this.num = num;
        this.arrayList = arrayList;
    }

    public boolean getAllAccount(Account account1, Account account2) {
        synchronized (arrayList) {
            if(!arrayList.contains(account1) && !arrayList.contains(account2)) {
                arrayList.add(account1);
                arrayList.add(account2);
                return true;
            }
            return false;
        }
    }

    public void freeAllAccount(Account account1, Account account2) {
        synchronized (arrayList) {
            arrayList.remove(account1);
            arrayList.remove(account2);
        }
    }

    @Override
    public void run() {

        synchronized (arrayList) {
            while(!getAllAccount(account1, account2)) {
                try {
                    arrayList.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("获取到了所有资源!!!");
        synchronized (account1) {
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (account2) {
                if(account1.subMoney(num)) {
                    account2.addMoney(num);
                }
            }
        }
        synchronized (arrayList) {
            freeAllAccount(account1, account2);
            arrayList.notifyAll();
        }
    }
}

Test.java

package com.zcyt085.synchronizedtest.demo6;

import java.util.ArrayList;

/**
 * 死锁解决方法1
 * 破坏产生死锁的必要条件——占有且等待
 *  方式是一次性申请所有的资源
 *  如果申请不到所有的资源
 *  就一个资源都不分配
 *
 *  使用等待/通知机制来优化循环获取全部资源
 * @author tu
 */
public class Test {
    public static void main(String[] args) throws InterruptedException {
        Account account1 = new Account(1000);
        Account account2 = new Account(1000);
        ArrayList<Account> arrayList = new ArrayList<>();
        MyThread myThread1 = new MyThread(account1, account2, 100, arrayList);
        MyThread myThread2 = new MyThread(account2, account1, 100, arrayList);
        myThread1.start();
        myThread2.start();
        myThread1.join();
        myThread2.join();
        System.out.println("账户1的余额:" + account1.getMoney() + "账户2的余额:" + account2.getMoney());
    }
}

上述的代码,相较于上一篇,区别在于对while(!getAllAccount(account1, account2))的执行添加了锁,并且在没申请到资源的情况下,调用arrayList.wait()来将当前线程添加到arrayList的等待队列中去;对freeAllAccount(account1, account2)的执行也添加锁,释放资源后,调用arrayList.notifyAll()来唤醒arrayList等待队列中等待的线程。

需要注意的是:锁和等待队列是一一对应的关系;当等待队列中的线程被唤醒后,仍需要重新获取锁,因为其在执行wait()时,就把锁给释放掉了;等待队列中的线程获取到锁后,会从其调用wait()后继续执行,而在这之间,可能发生其他线程插队而导致资源又不满足的情况,所以,一般会使用无限循环来获取资源,当资源仍不满足时,再次进入等待队列。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值