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