Java Reference
In-Depth Information
«interface»
java.lang.Runnable
100
1
1
1
AddAPennyTask
AccountWithoutSync
Account
+run(): void
-account: Account
-balance: int
+main(args: String[]): void
+getBalance(): int
+deposit(amount: int): void
F
IGURE
30.9
AccountWithoutSync
contains an instance of
Account
and 100 threads of
AddAPennyTask
.
L
ISTING
30.4
AccountWithoutSync.java
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();
create executor
8
9
// Create and launch 100 threads
10
for
(
int
i =
0
; i <
100
; i++) {
11
executor.execute(
new
AddAPennyTask());
submit task
12 }
13
14
executor.shutdown();
shut down executor
15
16
// Wait until all tasks are finished
17
while
(!executor.isTerminated()) {
18 }
19
20 System.out.println(
"What is balance? "
+ account.getBalance());
21 }
22
23
// A thread for adding a penny to the account
24
private static class
AddAPennyTask
implements
Runnable {
25
public void
run() {
26 account.deposit(
1
);
27 }
28 }
29
30
wait for all tasks to terminate
// An inner class for account
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
// This delay is deliberately added to magnify the
Search WWH ::
Custom Search