如何使用wait和notifyAll暂停函数,直到值增加到一定数量以上

问题描述

我正在编写的程序有一个小问题,它是一个银行模拟器,而我遇到的特定部分与以下两个功能有关:

下面的代码在Account类中:

    public synchronized boolean withdraw(int amount){
        try{
            System.out.println("Balance = " + balance + " amount = "+ amount);
            while(amount > balance){
                wait();
            }
        }
        catch (InterruptedException e){
            e.printstacktrace();
        }
        int currentBalance = balance;
        //Thread.yield(); // Try to force collision
        int newBalance = currentBalance - amount;
        balance = newBalance;
        return true;
    }
    public synchronized void deposit(int amount) {
        int currentBalance = balance;
        Thread.yield();   // Try to force collision
        int newBalance = currentBalance + amount;
        balance = newBalance;
        notifyAll();
    }

编辑后添加以下内容

银行类是调用取款和存款功能的地方:这是该代码

    public void transfer(int from,int to,int amount) {
        synchronized (this) {
            counter++;
            try {
                while (isTesting) {
                    wait();
                }
            } catch (InterruptedException e) {
                e.printstacktrace();
            }
            if (accounts[from].withdraw(amount)) {
                accounts[to].deposit(amount);
            }
       
            counter--;
            notifyAll();

            if (shouldtest()) test();
        }
    }

transfer()中的wait()调用工作得很好,我认为我不应该担心它的功能。但是如您所见,第一个调用取款的检查将检查该交易是否可以发生,如果可以,它将返回true并继续进行存款。实际运行该程序时,任何线程中的余额均低于金额时,该程序将冻结,不会切换到另一个线程,我已经用print语句确认了这一点。

基本上,我需要提取功能来检查当前帐户的余额,如果余额低于要提取的金额,它将等待其他帐户中的可用资金进行存款。

我希望存款能够从其他线程接受资金,并调用notifyAll()函数唤醒当前正在等待的线程,并再次检查条件。不幸的是,每当调用wait函数时,程序将完全停止挂起,并且根据调试器,所有其他线程都处于监视状态。

我真的很感谢您的帮助,如果您对我的代码有任何疑问,或者希望我添加更多内容,请随时问我,我将编辑问题。如果已经有另一个线程在问相同的问题,您可以帮我找到它吗?我已经在网上搜索过,但没有发现对我的情况有所帮助。非常感谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)