This Java project demonstrates a multi-threaded account simulation using concurrent programming concepts such as ExecutorService, Locks, and Conditions.
The AccountWithConditionUsers class simulates a user account with two concurrent operations:
- Adding money to the account
- Removing money from the account
These operations are performed by two separate threads, demonstrating thread safety and coordination using ReentrantLock and Condition.
UserAccount: A class representing the user's account with methods to add and remove money.AddMoney: ARunnableimplementation that simulates adding random amounts of money to the account.RemoveMoney: ARunnableimplementation that simulates removing random amounts of money from the account.
- Concurrent execution of add and remove operations
- Thread-safe account balance management
- Condition-based waiting when attempting to remove more money than the current balance
- Random amounts for add and remove operations
- Timed execution (60 seconds) using
ExecutorService
- The program creates an
ExecutorServicewith a fixed thread pool of 2 threads. - It submits
AddMoneyandRemoveMoneytasks to the executor. - The executor runs for 60 seconds, during which:
AddMoneythread adds random amounts to the account every 2 seconds.RemoveMoneythread attempts to remove random amounts from the account every 2 seconds.
- If the removal amount exceeds the current balance, the thread waits until sufficient funds are available.
- After 60 seconds, the executor is shut down, and the program terminates.
To run this project:
- Ensure you have Java Development Kit (JDK) installed on your system.
- Compile the Java file:
javac org/vinam/AccountWithConditionUsers.java - Run the compiled class:
java org.vinam.AccountWithConditionUsers
The program will output the add and remove operations, along with the current balance, for 60 seconds. Example output:
Added: 5 Current balance: 5
Removed: 3 Current balance: 2
Added: 7 Current balance: 9
Insufficient Balance while removing: 10
Added: 6 Current balance: 15
Removed: 10 Current balance: 5
- This project is for demonstration purposes and simulates a simplified version of concurrent account operations.
- The use of
ReentrantLockandConditionensures thread-safe operations on the shared account balance. - The project runs for a fixed duration of 60 seconds. You can modify this in the
mainmethod if needed.