Repository navigation
Expand file tree
/
Copy pathAdvancedMultithreadingDemo .java
More file actions
91 lines (76 loc) · 3.13 KB
/
Copy pathAdvancedMultithreadingDemo .java
File metadata and controls
91 lines (76 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class AdvancedMultithreadingDemo {
// Shared resource
static class BankAccount {
private double balance = 1000.0;
private final Lock lock = new ReentrantLock();
public void deposit(double amount) {
lock.lock();
try {
balance += amount;
System.out.println(Thread.currentThread().getName() + " deposited " + amount +
" | Balance: " + balance);
} finally {
lock.unlock();
}
}
public void withdraw(double amount) {
lock.lock();
try {
if (balance >= amount) {
balance -= amount;
System.out.println(Thread.currentThread().getName() + " withdrew " + amount +
" | Balance: " + balance);
} else {
System.out.println(Thread.currentThread().getName() + " tried to withdraw " + amount +
" | Insufficient balance!");
}
} finally {
lock.unlock();
}
}
public double getBalance() {
return balance;
}
}
public static void main(String[] args) throws Exception {
BankAccount account = new BankAccount();
ExecutorService executor = Executors.newFixedThreadPool(4);
CountDownLatch latch = new CountDownLatch(4);
// Callable tasks
List<Callable<Void>> tasks = Arrays.asList(
() -> { account.deposit(200); latch.countDown(); return null; },
() -> { account.withdraw(100); latch.countDown(); return null; },
() -> { account.deposit(300); latch.countDown(); return null; },
() -> { account.withdraw(500); latch.countDown(); return null; }
);
// Submit tasks
for (Callable<Void> task : tasks) {
executor.submit(task);
}
// Wait for all tasks to finish
latch.await();
System.out.println("\nAll basic transactions completed.\n");
// Demonstrate CompletableFuture for async operations
CompletableFuture<Double> interestCalculation = CompletableFuture.supplyAsync(() -> {
System.out.println("Calculating interest asynchronously...");
try { Thread.sleep(1500); } catch (InterruptedException e) {}
return account.getBalance() * 0.05;
}).thenApply(interest -> {
System.out.println("Interest calculated: " + interest);
return interest;
});
double interest = interestCalculation.get();
account.deposit(interest);
// Demonstrate Future with Callable
Future<Double> balanceFuture = executor.submit(() -> {
Thread.sleep(1000);
return account.getBalance();
});
System.out.println("\nFinal balance after interest: " + balanceFuture.get());
executor.shutdown();
System.out.println("\nExecutor shutdown gracefully.");
}
}