Solve Concurrency Issues (Synchronized Methods)

master
Hammy 4 years ago
parent 972c5de903
commit e948870277

@ -0,0 +1,17 @@
package multi.threading.solving.concurrency.issues;
public class BankAccount {
private int balance;
public BankAccount(int balance) {
this.balance = balance;
}
public synchronized int getBalance() {
return balance;
}
public synchronized void deposit(int amount) {
balance += amount;
}
}

@ -0,0 +1,23 @@
package multi.threading.solving.concurrency.issues;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(5);
BankAccount account = new BankAccount(100);
for (int i = 0; i < 5; i++) {
Worker worker = new Worker(account);
executorService.submit(worker);
}
executorService.shutdown();
if (executorService.awaitTermination(60, TimeUnit.SECONDS)) {
System.out.println("Operations Executed Successfully!");
}
}
}

@ -0,0 +1,17 @@
package multi.threading.solving.concurrency.issues;
public class Worker implements Runnable {
private final BankAccount account;
public Worker(BankAccount account) {
this.account = account;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
account.deposit(10);
System.out.println("End Balance: " + account.getBalance());
}
}
}
Loading…
Cancel
Save