简体   繁体   English

Java锁定条件等待和通知:IllegalMonitorStateException

[英]Java Lock Condition Wait and Notify: IllegalMonitorStateException

I am new to Java. 我是Java新手。 I just read the "core java" book. 我刚刚读了“核心Java”书。 I met a issue about 'Condition & Lock'. 我遇到了有关“条件与锁定”的问题。

I typed a piece of code from the book to the eclipse to do some practice. 我输入了从书本到日食的一段代码来进行一些练习。

When I run the code ,the line of "sufficientFund.wait();" 当我运行代码时,“ sufficientFund.wait();”行 throws an IllegalMonitorStateException. 引发IllegalMonitorStateException。 Why here has an exception? 为什么这里有例外?

I hava googled for a while, I know that "This method should only be called by a thread that is the owner of this object's monitor." 我已经搜索了一段时间,我知道“该方法只能由作为该对象监视器的所有者的线程调用。” I think the current thread has the lock, because the 'bankLock.lock();' 我认为当前线程具有锁定,因为“ bankLock.lock();” is executed just before wait(). 在wait()之前执行。 I think the correct behavior of the code is, the current thread should be hung at the sufficientFund.wait(), but it didn't. 我认为代码的正确行为是,当前线程应该挂在足够的Fund.wait()上,但事实并非如此。

package com.first.java;

import java.util.Scanner;
import java.util.concurrent.locks.*;

public class BankTranf {

    private static final int NACCOUNT = 3;
    public static final double INITAL_BALANCE = 1000;

    public static void main(String[] args) {

        Bank bank = new Bank(NACCOUNT, INITAL_BALANCE);

        for (int i = 0; i < NACCOUNT; i++) {

            TransferRunnable transferRunnable = new TransferRunnable(bank, i, INITAL_BALANCE);

            Thread thread = new Thread(transferRunnable);
            thread.start();
        }

        System.out.println("press any key to exit.");
        Scanner in = new Scanner(System.in);
        in.nextLine();
        System.exit(0);
    }

}

class Bank {
    private final double[] account;
    private Lock bankLock;
    private Condition sufficientFund;

    public Bank(int n, double initialBanlance) {
        account = new double[n];
        for (int i = 0; i < account.length; i++) {
            account[i] = initialBanlance;
        }

        bankLock = new ReentrantLock();
        sufficientFund = bankLock.newCondition();

    }

    public void transfer(int from, int to, double amount) {
        bankLock.lock();

        try {
            while (account[from] < amount) {
                System.out.println(Thread.currentThread().getName() + " does'nt hava enough money");
                sufficientFund.wait();
            }

            System.out.println(Thread.currentThread());

            account[from] -= amount;
            System.out.printf("%10.2f from %d to %d ", amount, from, to);
            account[to] += amount;
            System.out.printf(" Total balance: %10.2f%n", getTotalBalance());
            sufficientFund.signalAll();

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            bankLock.unlock();
        }
    }

    public double getTotalBalance() {
        double d = 0;
        bankLock.lock();
        try {
            for (double n : account) {
                d += n;
            }
            return d;
        } finally {
            bankLock.unlock();
        }
    }

    public int size() {
        return account.length;
    }

}

class TransferRunnable implements Runnable {

    private Bank bank;
    private int fromAccount;
    private double maxAmount;
    private int DELAY = 10;

    public TransferRunnable(Bank b, int from, double max) {
        bank = b;
        this.fromAccount = from;
        this.maxAmount = max;
    }

    @Override
    public void run() {

        try {
            while (true) {
                int toAcount = (int) (bank.size() * Math.random());
                double amount = maxAmount * Math.random();
                bank.transfer(fromAccount, toAcount, amount);
                Thread.sleep(4000/* (int)(DELAY*Math.random()) */);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

I also tried another way, I remove all the Lock and Condition, instead of using "synchronized", the code was running as I expected. 我还尝试了另一种方法,即删除了所有的Lock和Condition,而不是使用“ synchronized”,而是代码按预期运行。

public synchronized void transfer(int from, int to, double amount) {
        //bankLock.lock();

        try {
            while (account[from] < amount) {
                System.out.println(Thread.currentThread().getName() + " does'nt hava enough money");

                wait();
            }

            System.out.println(Thread.currentThread());

            account[from] -= amount;
            System.out.printf("%10.2f from %d to %d ", amount, from, to);
            account[to] += amount;
            System.out.printf(" Total balance: %10.2f%n", getTotalBalance());

            notifyAll();

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {

        }
    }

    public synchronized double getTotalBalance() {
        double d = 0;

        try {
            for (double n : account) {
                d += n;
            }
            return d;
        } finally {

        }
    }

请注意, Condition作为Java中的任何类都扩展了Object ,因此它具有从Object继承的wait方法,我相信您在这里错误地调用了该方法,您要在条件上等待的方法是Condition#await而不是wait

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM