Java Reference
In-Depth Information
12
// construct a SimpleArray of a given size
13
public SimpleArray( int size)
14
{
15
array = new int [size];
16
}
17
18
// add a value to the shared array
19
public void add( int value)
20
{
21
int position = writeIndex; // store the write index
22
23
try
24
{
25
// put thread to sleep for 0-499 milliseconds
26
Thread.sleep(generator.nextInt( 500 ));
27
}
28
catch (InterruptedException ex)
29
{
30
Thread.currentThread().interrupt(); // re-interrupt the thread
31
}
32
33
// put value in the appropriate element
array[position] = value;
34
35
System.out.printf( "%s wrote %2d to element %d.%n" ,
36
Thread.currentThread().getName(), value, position);
37
38
++writeIndex; // increment index of element to be written next
39
System.out.printf( "Next write index: %d%n" , writeIndex);
40
}
41
42
// used for outputting the contents of the shared integer array
43
public String toString()
44
{
45
return Arrays.toString(array);
46
}
47
} // end class SimpleArray
Fig. 23.5 | Class that manages an integer array to be shared by multiple threads. ( Caution: The
example of Figs. 23.5-23.7 is not thread safe.) (Part 2 of 2.)
Method add (lines 19-40) allows new values to be inserted at the end of the array.
Line 21 stores the current writeIndex value. Line 26 puts the thread that invokes add to
sleep for a random interval from 0 to 499 milliseconds. This is done to make the problems
associated with unsynchronized access to shared mutable data more obvious. After the thread
is done sleeping, line 34 inserts the value passed to add into the array at the element spec-
ified by position . Lines 35-36 output a message indicating the executing thread's name,
the value that was inserted in the array and where it was inserted. The expression
Thread.currentThread().getName() (line 36) first obtains a reference to the currently
executing Thread , then uses that Thread 's getName method to obtain its name. Line 38
increments writeIndex so that the next call to add will insert a value in the array's next
element. Lines 43-46 override method toString to create a String representation of the
array's contents.
 
Search WWH ::




Custom Search