Java Reference
In-Depth Information
so can be invoked indiscriminately by anyone with access to your ob-
jectsomething you usually don't desire. For example, we definitely don't
want clients to invoke the
run
method of
PrintServer
. One solution is to
use
Thread.currentThread
to establish the identity of the thread that in-
vokes
run
and to compare it with the intended worker thread. But a sim-
pler solution is not to implement
Runnable
, but to define an inner
Runnable
object. For example, we can rewrite
PrintServer
as follows:
class PrintServer2 {
private final PrintQueue requests = new PrintQueue();
public PrintServer2() {
Runnable service = new Runnable() {
public void run() {
for(;;)
realPrint(requests.remove());
}
};
new Thread(service).start();
}
public void print(PrintJob job) {
requests.add(job);
}
private void realPrint(PrintJob job) {
// do the real work of printing
}
}
The
run
method is exactly the same as before, but now it is part of an
anonymous inner class that implements
Runnable
. When the thread is
created we pass
service
as the
Runnable
to execute. Now the work to be
performed by the thread is completely private and can't be misused.
Using
Runnable
objects you can create very flexible multithreaded
designs. Each
Runnable
becomes a unit of work and each can be passed
around from one part of the system to another. We can store
Runnable
objects in a queue and have a pool of worker threads servicing the work