Created
October 5, 2015 06:47
-
-
Save vaibhav-jani/891cab89bef2a86977a2 to your computer and use it in GitHub Desktop.
Simple example of the race condition in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class ThreadSynchronisationDemo implements Runnable { | |
| private Account acct = new Account(); | |
| public static void main(String[] args) { | |
| ThreadSynchronisationDemo r = new ThreadSynchronisationDemo(); | |
| Thread one = new Thread(r); | |
| Thread two = new Thread(r); | |
| one.setName("Fred"); | |
| two.setName("Lucy"); | |
| one.start(); | |
| two.start(); | |
| } | |
| public void run() { | |
| for (int x = 0; x < 5; x++) { | |
| makeWithdrawal(10); | |
| if (acct.getBalance() < 0) { | |
| System.out.println("account is overdrawn!"); | |
| } | |
| } | |
| } | |
| private /*synchronized*/ void makeWithdrawal(int amt) { | |
| if (acct.getBalance() >= amt) { | |
| System.out.println(Thread.currentThread().getName() + " is going to withdraw"); | |
| try { | |
| Thread.sleep(500); | |
| } catch(InterruptedException ex) { } | |
| acct.withdraw(amt); | |
| System.out.println(Thread.currentThread().getName() + " completes the withdrawal"); | |
| } else { | |
| System.out.println("Not enough in account for " + Thread.currentThread().getName() + " to withdraw " + acct.getBalance()); | |
| } | |
| } | |
| class Account { | |
| private int balance = 50; | |
| public int getBalance() { | |
| return balance; | |
| } | |
| public void withdraw(int amount) { | |
| balance = balance - amount; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment