1 import java.util.concurrent.*;
2 import java.util.concurrent.locks.*;
3
4 public class AccountWithSyncUsingLock {
5 private static Account account = new Account();
6
7 public static void main(String[] args) {
8 ExecutorService executor = Executors.newCachedThreadPool();
9
10
11 for (int i = 0; i < 100; i++) {
12 executor.execute(new AddAPennyTask());
13 }
14
15 executor.shutdown();
16
17
18 while (!executor.isTerminated()) {
19 }
20
21 System.out.println("What is balance ? " + account.getBalance());
22 }
23
24
25 public static class AddAPennyTask implements Runnable {
26 public void run() {
27 account.deposit(1);
28 }
29 }
30
31
32 public static class Account {
33 private static Lock lock = new ReentrantLock();
34 private int balance = 0;
35
36 public int getBalance() {
37 return balance;
38 }
39
40 public void deposit(int amount) {
41 lock.lock();
42
43 try {
44 int newBalance = balance + amount;
45
46
47
48 Thread.sleep(5);
49
50 balance = newBalance;
51 }
52 catch (InterruptedException ex) {
53 }
54 finally {
55 lock.unlock();
56 }
57 }
58 }
59 }