What is a race condition?

后端 未结 18 2505
谎友^
谎友^ 2020-11-21 04:52

When writing multithreaded applications, one of the most common problems experienced is race conditions.

My questions to the community are:

What is the rac

18条回答
  •  别跟我提以往
    2020-11-21 05:27

    Here is the classical Bank Account Balance example which will help newbies to understand Threads in Java easily w.r.t. race conditions:

    public class BankAccount {
    
    /**
     * @param args
     */
    int accountNumber;
    double accountBalance;
    
    public synchronized boolean Deposit(double amount){
        double newAccountBalance=0;
        if(amount<=0){
            return false;
        }
        else {
            newAccountBalance = accountBalance+amount;
            accountBalance=newAccountBalance;
            return true;
        }
    
    }
    public synchronized boolean Withdraw(double amount){
        double newAccountBalance=0;
        if(amount>accountBalance){
            return false;
        }
        else{
            newAccountBalance = accountBalance-amount;
            accountBalance=newAccountBalance;
            return true;
        }
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        BankAccount b = new BankAccount();
        b.accountBalance=2000;
        System.out.println(b.Withdraw(3000));
    
    }
    

提交回复
热议问题