img
. .
Add a bit of Thread-Specific Data.
*/
import java.io.*;
import java.util.*;
import Extensions.*;
public class TSDThread extends Thread {
boolean inCriticalSection = true;
public TSDThread(Searcher o) {
super(o);
}
}
The method doDatabaseThing() uses the technique described in Code Example 9-7 to ensure
that it runs atomically. In addition, you will notice that when the answer is found, the finder locks
a synchronized section for the cancel object. In case some other thread already found the answer,
our thread will enter this critical section, see that cancel.found is true, and exit by itself. [It
is perfectly possible for two threads to find the answer independently and the interruption which
the first sends to the second not to be seen by the second thread until later. So we need to check
this variable. Alternatively, we could reasonably have called Thread.interrupted().]
Each of the searcher threads calls doDatabaseThing() during the loop, so you don't have to
worry about them never seeing the interruption. The main thread looks for the result in the global
variable answer. It prints out success, noting the number of attempts required, then waits for all
the searchers to exit. When they have all exited, it repeats the process.[5] Simple? Well...
[5]
This is pretty ugly code. We'll fix it up in a bit.
Using Cancellation
You've seen the definition of cancellation. Now how can you use it effectively? The answer is,
"not easily!"
First, let us consider your objectives in using cancellation. You created some threads to
accomplish a task, and now you don't need them to work on it any longer. Perhaps the task has
already been accomplished, or perhaps the user has changed her mind. Normally, we use
cancellation to stop threads because we don't want them to waste time on something unnecessary.
This is the best case. Sometimes we want to use cancellation to prevent threads from doing
something that we no longer desire. This is harder.
In cancelling a thread, what do you want? Do you want to:
1.
Kill it instantly?
2.
Kill it in bounded CPU time?
3.
Prevent it from making any more global changes?
4.
Prevent it from wasting CPU time?
Presumably you want goal 4, generally implying goal 2. After all, if you don't care whether the
CPU time is bounded, why bother cancelling the thread at all?
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home