The main thread gets the PID and creates 10 threads to search for it. Each of the searcher threads
proceeds to generate a random number, checking to see if that happens to be the PID. When one
thread finds the number, it interrupts all the other threads, then returns itself. The main thread will
do a join on all the searcher threads, printing out the answer when all have exited.
Example 9-11 Using interrupt() to Cancel Searcher Threads
// CancellationInterrupt/Cancellation.java
/*
A very simple example to run which illustrate cancellation.
Choose a target number, then create a bunch of threads to search
for using a heuristic [call rand()!].  The first to find it
cancels
the others.
A database is included to illustrate typical problems.  The
database
should always by 0 at the end of every transaction.  Observe how
much effort that takes.
*/
import java.io.*;
import Extensions.*;
public class Cancellation {
int
answer = 0;
int
target = 9;
boolean
found = false;
int
nSearchers = 10;
TSDThread
threads[] = new TSDThread[nSearchers];
Object
databaseBalancedLock = new Object();
int
databaseBalanced = 0;
Object
nGuessesLock = new Object();
int
nGuesses = 0;
static
boolean DEBUG = false;
public static void main(String argv[]) throws
InterruptedException {
Cancellation c = new Cancellation();
if (System.getProperty("DEBUG") != null)
DEBUG = true;
for (int i = 0; i < 2; i++) {
c.run();
}
}
public void incrementGuesses() {
synchronized(nGuessesLock) {
nGuesses++;
}
// Cannot synchronize on cancel. Why?
}
public void incrementDatabase(int i) {
if (DEBUG) {
System.out.println(Thread.currentThread().getName()
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home