Java Reference
In-Depth Information
4
import
java.util.concurrent.ExecutorService;
5
import
java.util.concurrent.TimeUnit;
6
7
public class
SharedArrayTest
8
{
9
public static void
main(String[] arg)
10
{
11
// construct the shared object
12
SimpleArray sharedSimpleArray =
new
SimpleArray(
6
);
13
14
// create two tasks to write to the shared SimpleArray
15
ArrayWriter writer1 =
new
ArrayWriter(
1
, sharedSimpleArray);
16
ArrayWriter writer2 =
new
ArrayWriter(
11
, sharedSimpleArray);
17
18
// execute the tasks with an ExecutorService
19
ExecutorService executorService = Executors.newCachedThreadPool();
20
executorService.execute(writer1);
21
executorService.execute(writer2);
22
23
executorService.shutdown();
24
25
try
26
{
27
// wait 1 minute for both writers to finish executing
28
boolean
tasksEnded =
executorService.awaitTermination(
1
,
TimeUnit.MINUTES
);
29
30
31
if
(tasksEnded)
32
{
33
System.out.printf(
"%nContents of SimpleArray:%n"
);
34
System.out.println(sharedSimpleArray);
// print contents
35
}
36
else
37
System.out.println(
38
"Timed out while waiting for tasks to finish."
);
39
}
40
catch
(InterruptedException ex)
41
{
42
ex.printStackTrace();
43
}
44
}
// end main
45
}
// end class SharedArrayTest
pool-1-thread-1 wrote 1 to element 0.
Next write index: 1
pool-1-thread-1 wrote 2 to element 1.
Next write index: 2
pool-1-thread-1 wrote 3 to element 2.
Next write index: 3
First
pool-1-thread-1
wrote the value
1
to element
0
. Later
pool-1-thread-2
wrote the value
11
to element
0
, thus
overwriting
the previously stored value.
pool-1-thread-2 wrote 11 to element 0.
Next write index: 4
Fig. 23.7
|
Executing two
Runnable
s to add elements to a shared array. (
Caution:
The example
of Figs. 23.5-23.7 is
not
thread safe.) (Part 2 of 3.)