notes on 14.2 using Runnable
from Gosling etc.. 's "The Java Programming Language , 4ed"
1.The work done by a thread is oackaged up in its run() method.
2. You can execute a Runnable object in its own thread by passing it to a thread constructor. If a thread object is constructed with a runnable object, the implementation of Thread.run will invoke the runnable object's run() method.
3. Real classes define complete state and behaviour, where having something execute in a separate thread is only a part of theit functionality.
4. Eg. new thread(this).start();
--While we didn't keep a reference to the thread, when the thread itself was created, it stored a reference to itself in its ThreadGroup.
5. We can place the run() method in part of an anonymous inner class (interface based) that implements Runnable. Eg.
...
public PrintServer2()
{
// constructor
Runnable service =
new Runnable() {
public void run() {
for(;;)
realPrint(request.remove() );
}
}; // queer
new Thread(sevice).start();
}
...
6. Using Runnable objects, you can create very flexible multithreaded designs. Each Runnable becomes a unit of work and each can be passed from one part of the system to another.
7. We can store Runnable objects in a queue and have a pool of worker threads servicing the work requests in the queue-- a very common design used in multithreaded server applications.
Keine Kommentare:
Kommentar veröffentlichen