img
.
Random r = new Random(seed);
int guess;
System.out.println(t.getName() + " is searching...");
for (int i = 0; i < 1000000; i++) {// Better never hit 1000000!
doDatabaseThing();
synchronized(cancel) {
if (cancel.found)
break;
}
guess = r.nextInt() % 1000;
cancel.incrementGuesses();
if (guess == target) {
System.out.println(t.getName() + " got the answer:" +
cancel.answer);
synchronized(cancel) {
if (cancel.found)
break;
cancel.answer = guess;
cancel.found = true;
break;
}
}
}
cancel.barrier.barrierPost();
return;
}
This polling example sure looks a lot simpler compared to the complexity of the previous
examples, and it is. But it is also much less generally useful because many interesting programs
involve unbounded blocking calls. Thus any kind of server program will invariably be calling
read() on a socket, and there is no guarantee if or when that call will return. So use polling if
you can, but you'll probably be stuck with using interruption.
APIs Used in This Chapter
The Class java.lang.Thread
interrupt
public void interrupt()
This sets the interrupt flag and causes the target thread to throw an InterruptedException if
it is blocked on (or as soon as it executes) an interruptible method or
InterruptedIOException if it is blocked on I/O.
Reference:
Chapter 9.
interrupted
public static boolean interrupted()
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home