Java Reference
In-Depth Information
1
// Fig. 23.8: SimpleArray.java
2
// Class that manages an integer array to be shared by multiple
3
// threads with synchronization.
4
import java.security.SecureRandom;
5
import java.util.Arrays;
6
7
public class SimpleArray
8
{
9
private static final SecureRandom generator = new SecureRandom();
10
private final int [] array; // the shared integer array
11
private int writeIndex = 0 ; // index of next element to be written
12
13
// construct a SimpleArray of a given size
14
public SimpleArray( int size)
15
{
16
array = new int [size];
17
}
18
19
// add a value to the shared array
20
public synchronized void add( int value)
21
{
22
int position = writeIndex; // store the write index
23
24
try
25
{
26
// in real applications, you shouldn't sleep while holding a lock
27
Thread.sleep(generator.nextInt( 500 )); // for demo only
28
}
29
catch (InterruptedException ex)
30
{
31
Thread.currentThread().interrupt();
32
}
33
34
// put value in the appropriate element
35
array[position] = value;
36
System.out.printf( "%s wrote %2d to element %d.%n" ,
37
Thread.currentThread().getName(), value, position);
38
39
++writeIndex; // increment index of element to be written next
40
System.out.printf( "Next write index: %d%n" , writeIndex);
41
}
42
43
// used for outputting the contents of the shared integer array
44
public synchronized String toString()
45
{
46
return Arrays.toString(array);
47
}
48
} // end class SimpleArray
Fig. 23.8 | Class that manages an integer array to be shared by multiple threads with
synchronization. (Part 1 of 2.)
Search WWH ::




Custom Search