Java Reference
In-Depth Information
2. public void execute();
3. }
The ConcreteQueue class implements the Queue and provides a worker thread to operate on the RunnableTask
objects. The inner class defined for ConcreteQueue , Worker , has a run method that continually searches the
queue for new tasks to perform. When a task becomes available, the worker thread pops the RunnableTask off
the queue and runs its execute method.
Example 4.12 ConcreteQueue.java
1. import java.util.Vector;
2. public class ConcreteQueue implements Queue{
3. private Vector tasks = new Vector();
4. private boolean waiting;
5. private boolean shutdown;
6.
7. public void setShutdown(boolean isShutdown){ shutdown = isShutdown; }
8.
9. public ConcreteQueue(){
10. tasks = new Vector();
11. waiting = false;
12. new Thread(new Worker()).start();
13. }
14.
15. public void put(RunnableTask r){
16. tasks.add(r);
17. if (waiting){
18. synchronized (this){
19. notifyAll();
20. }
21. }
22. }
23.
24. public RunnableTask take(){
25. if (tasks.isEmpty()){
26. synchronized (this){
27. waiting = true;
28. try{
29. wait();
30. } catch (InterruptedException ie){
31. waiting = false;
32. }
33. }
34. }
35. return (RunnableTask)tasks.remove(0);
36. }
37.
38. private class Worker implements Runnable{
39. public void run(){
40. while (!shutdown){
41. RunnableTask r = take();
42. r.execute();
43. }
44. }
45. }
46. }
Two classes, AddressRetriever and ContactRetriever , implement the RunnableTask interface in this
example. The classes are very similar; both use RMI to request that a business object be retrieved from a server.
As their names suggest, each class retrieves a specific kind of business object, making Address and Contact
objects from the server available to clients.
Example 4.13 AddressRetriever.java
1. import java.rmi.Naming;
2. import java.rmi.RemoteException;
3. public class AddressRetriever implements RunnableTask{
4. private Address address;
5. private long addressID;
6. private String url;
7.
8. public AddressRetriever(long newAddressID, String newUrl){
9. addressID = newAddressID;
10. url = newUrl;
11. }
12.
Search WWH ::




Custom Search