Solve Concurrency Issues (Synchronized Block Statements)
parent
4be5cde864
commit
16fdd49a8c
@ -0,0 +1,17 @@
|
||||
package multi.threading.solving.concurrency.issues.with.synchronised.blocks;
|
||||
|
||||
public class BankAccount {
|
||||
private int balance;
|
||||
|
||||
public BankAccount(int balance) {
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
public int getBalance() {
|
||||
return balance;
|
||||
}
|
||||
|
||||
public void deposit(int amount) {
|
||||
balance += amount;
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package multi.threading.solving.concurrency.issues.with.synchronised.blocks;
|
||||
|
||||
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 <= 10; 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,19 @@
|
||||
package multi.threading.solving.concurrency.issues.with.synchronised.blocks;
|
||||
|
||||
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++) {
|
||||
synchronized(account) {
|
||||
account.deposit(10);
|
||||
}
|
||||
System.out.println("End Balance: " + account.getBalance());
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue