Java Reference
In-Depth Information
Worker Thread
In a typical application, certain jobs have to be done. It's not always important that they happen now, just that
they do happen. You can compare this to cleaning a house. It's not important that it happen at a particular time, as
long as somebody does it sometime this week—or month, or year, depending on your standards.
This example uses a Queue to hold tasks. The Queue interface defines two basic methods, put and take . These
methods are used to add and remove tasks, represented by the RunnableTask interface, on the Queue .
Example A.215 Queue.java
1. public interface Queue{
2. void put(RunnableTask r);
3. RunnableTask take();
4. }
Example A.216 RunnableTask.java
1. public interface RunnableTask{
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 A.217 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. }
 
Search WWH ::




Custom Search