Quantcast
Channel: What is a race condition? - Stack Overflow
Viewing all articles
Browse latest Browse all 20

Answer by realPK for What is a race condition?

$
0
0

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));}

Viewing all articles
Browse latest Browse all 20

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>