Java Reference
In-Depth Information
private
private void
void demo () {
// Start two reader threads
for
for ( int
int i = 0 ; i < NUM_READER_THREADS ; i ++) {
new
new Thread () {
public
public void
void run () {
while
while (! done ) {
lock . readLock (). lock ();
try
try {
theData . forEach ( p ->
System . out . printf ( "%s: votes %d%n" ,
p . getName (),
p . getVotes ()));
} finally
finally {
// Unlock in "finally" to be sure it gets done.
lock . readLock (). unlock ();
}
try
try {
Thread . sleep ((( long
long )( Math . random ()* 1000 )));
} catch
catch ( InterruptedException ex ) {
// nothing to do
}
}
}
}. start ();
}
// Start one writer thread to simulate occasional voting
new
new Thread () {
public
public void
void run () {
while
while (! done ) {
lock . writeLock (). lock ();
try
try {
theData . voteFor (
// Vote for random candidate :-)
// Performance: should have one PRNG per thread.
((( int
int )( Math . random ()*
theData . getCandidateCount ()))));
} finally
finally {
lock . writeLock (). unlock ();
}
try
try {
Thread . sleep ((( long
long )( Math . random ()* 1000 )));
} catch
catch ( InterruptedException ex ) {
// nothing to do
Search WWH ::




Custom Search