Java多线程银行转账、同步问题

Java多线程银行转账、同步问题,java,multithreading,synchronization,bank,Java,Multithreading,Synchronization,Bank,我正在尝试多线程银行转账问题。但是,我在正确同步线程方面遇到了问题。线程在账户之间执行转账后,会定期进行测试,以确保没有任何资金获得或损失 当一个线程进入测试方法时,它应该设置一个标志来阻止任何其他线程进入Transfer方法,然后等待当前执行传输的所有线程结束 public void transfer(int from, int to, int amount) { //finish running all threads' current transactions be

我正在尝试多线程银行转账问题。但是,我在正确同步线程方面遇到了问题。线程在账户之间执行转账后,会定期进行测试,以确保没有任何资金获得或损失

当一个线程进入测试方法时,它应该设置一个标志来阻止任何其他线程进入Transfer方法,然后等待当前执行传输的所有线程结束

public void transfer(int from, int to, int amount) {        
    //finish running all threads' current transactions before test

    accounts[from].waitForAvailableFunds(amount);
    if (!open) return;    

    //checks to see if any thread is currently testing
    //if so, wait
    while(flag) {
        try {
            wait();
        } catch (InterruptedException e) { /*ignore*/ }
    }

    //do not execute these two statements when a thread
    //is performing a test
    if (accounts[from].withdraw(amount)) {
        accounts[to].deposit(amount);

    }  

    if (shouldTest() && !flag)   test();

}

//only one thread can perform a test at any given moment
public synchronized void test() {        

    //when test starts set a flag telling threads to
    //not begin any new transfers
    flag = true;

    //wait for all threads currently performing transfers
    //to finish current transfer before continuing


    int sum = 0;
    for (int i = 0; i < accounts.length; i++) {
        System.out.printf("%s %s%n", 
                Thread.currentThread().toString(),accounts[i].toString());
        sum += accounts[i].getBalance();
    }
    System.out.println(Thread.currentThread().toString() + 
            " Sum: " + sum);
    if (sum != numAccounts * initialBalance) {
        System.out.println(Thread.currentThread().toString() + 
                " Money was gained or lost");
        System.exit(1);
    } else {
        System.out.println(Thread.currentThread().toString() + 
                " The bank is in balance");
    }

    //reset flag and notify threads test is complete.
    flag = false;
    notifyAll();
}
首先,我甚至不确定我是否正确地设置了标志和等待。其次,我如何让进入测试方法的线程等待所有已经执行传输的其他线程完成当前传输


谢谢

我认为您应该使用volatile来装饰标志,以确保在不同线程中更改标志时它会受到影响