Java Reference
In-Depth Information
Class
ArrayWriter
Class
ArrayWriter
(Fig. 23.6) implements the interface
Runnable
to define a task for in-
serting values in a
SimpleArray
object. The constructor (lines 10-14) takes two argu-
ments—an integer
value
, which is the first value this task will insert in the
SimpleArray
object, and a reference to the
SimpleArray
object. Line 20 invokes method
add
on the
SimpleArray
object. The task completes after three consecutive integers beginning with
startValue
are inserted in the
SimpleArray
object.
1
// Fig. 23.6: ArrayWriter.java
2
// Adds integers to an array shared with other Runnables
3
import
java.lang.Runnable;
4
5
public class
ArrayWriter
implements
Runnable
6
{
7
private final
SimpleArray sharedSimpleArray;
8
private final int
startValue;
9
10
public
ArrayWriter(
int
value, SimpleArray array)
11
{
12
startValue = value;
13
sharedSimpleArray = array;
14
}
15
16
public void
run()
17
{
18
for
(
int
i = startValue; i < startValue +
3
; i++)
19
{
20
sharedSimpleArray.add(i);
// add an element to the shared array
21
}
22
}
23
}
// end class ArrayWriter
Fig. 23.6
|
Adds integers to an array shared with other
Runnable
s. (
Caution:
The example of
Figs. 23.5-23.7 is
not
thread safe.)
Class
SharedArrayTest
Class
SharedArrayTest
(Fig. 23.7) executes two
ArrayWriter
tasks that add values to a
single
SimpleArray
object. Line 12 constructs a six-element
SimpleArray
object. Lines
15-16 create two new
ArrayWriter
tasks, one that places the values 1-3 in the
Simple-
Array
object, and one that places the values 11-13. Lines 19-21 create an
ExecutorSer-
vice
and execute the two
ArrayWriter
s. Line 23 invokes the
ExecutorService
's
shutDown
method to
prevent additional tasks from starting
and to enable the application to
terminate when the currently executing tasks complete execution.
1
// Fig. 23.7: SharedArrayTest.java
2
// Executing two Runnables to add elements to a shared SimpleArray.
3
import
java.util.concurrent.Executors;
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 1 of 3.)