Commit 1f5b714
committed
feat: implement synchronized ATM access with multiple customers
WHAT the code does:
- Defines an ATM class with two synchronized methods:
- checkBalance() simulates balance inquiry with delay.
- withdraw() simulates cash withdrawal with delay.
- Customer class extends Thread:
- Holds name, amount, and ATM reference.
- Overrides run() to perform both checkBalance() and withdraw().
- ATMMoney main class:
- Creates one ATM instance.
- Spawns two Customer threads (Smith and John) using the same ATM.
- Starts both threads to simulate concurrent ATM usage.
WHY this matters:
- Demonstrates synchronization in Java to prevent race conditions when multiple threads access shared resources.
- Shows how synchronized methods ensure only one thread executes ATM operations at a time.
- Models a real-world case where multiple customers safely share a single ATM.
HOW it works:
1. ATM methods declared synchronized → implicit lock on ATM instance.
2. Each Customer thread executes useATM():
- First checks balance.
- Then withdraws specified amount.
3. Thread.sleep() simulates time delay (like processing transactions).
4. Because of synchronization:
- While one customer uses ATM, the other must wait.
- Prevents inconsistent or interleaved outputs.
Key points:
- `synchronized` ensures mutual exclusion.
- Threads share one ATM instance → critical section protection.
- Thread lifecycle: start() → run() → terminated.
Short key: java-threads synchronized-atm-multithreading demo.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent f4859fb commit 1f5b714
1 file changed
+13
-19
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
4 | | - | |
| 1 | + | |
| 2 | + | |
5 | 3 | | |
6 | 4 | | |
7 | 5 | | |
8 | 6 | | |
9 | | - | |
| 7 | + | |
10 | 8 | | |
11 | 9 | | |
12 | | - | |
13 | | - | |
| 10 | + | |
14 | 11 | | |
15 | 12 | | |
16 | 13 | | |
| |||
19 | 16 | | |
20 | 17 | | |
21 | 18 | | |
22 | | - | |
23 | | - | |
| 19 | + | |
24 | 20 | | |
25 | 21 | | |
26 | 22 | | |
27 | | - | |
28 | | - | |
| 23 | + | |
| 24 | + | |
29 | 25 | | |
30 | 26 | | |
31 | 27 | | |
32 | 28 | | |
33 | 29 | | |
34 | 30 | | |
35 | 31 | | |
36 | | - | |
37 | | - | |
| 32 | + | |
38 | 33 | | |
39 | 34 | | |
40 | 35 | | |
41 | | - | |
| 36 | + | |
| 37 | + | |
42 | 38 | | |
43 | 39 | | |
44 | 40 | | |
45 | 41 | | |
46 | 42 | | |
47 | | - | |
48 | | - | |
49 | | - | |
50 | | - | |
| 43 | + | |
| 44 | + | |
51 | 45 | | |
52 | 46 | | |
53 | 47 | | |
| |||
56 | 50 | | |
57 | 51 | | |
58 | 52 | | |
59 | | - | |
| 53 | + | |
0 commit comments