KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > foxtrot > workers > MultiWorkerThread


1 /**
2  * Copyright (c) 2002-2005, Simone Bordet
3  * All rights reserved.
4  *
5  * This software is distributable under the BSD license.
6  * See the terms of the BSD license in the documentation provided with this software.
7  */

8
9 package foxtrot.workers;
10
11 import java.util.List JavaDoc;
12 import java.util.LinkedList JavaDoc;
13
14 import foxtrot.Task;
15
16 /**
17  * Full implementation of {@link foxtrot.WorkerThread} that uses one or more threads to run
18  * {@link foxtrot.Task}s subclasses. <br />
19  * Tasks execution is parallelized: two tasks posted at the same time are executed in parallel
20  * by two different threads.
21  * This is done by using a mechanism similar to a classic web server threading: one thread
22  * waits for incoming tasks and a new thread is spawned to run the task.
23  * This ensures that the {@link #postTask} method returns immediately in any case.
24  * @version $Revision: 1.2 $
25  */

26 public class MultiWorkerThread extends SingleWorkerThread
27 {
28    private final List JavaDoc runners = new LinkedList JavaDoc();
29
30    protected String JavaDoc getThreadName()
31    {
32       return "Foxtrot Multi Worker Thread Runner #" + nextSequence();
33    }
34
35    protected void run(final Task task)
36    {
37       // No pooling, since the implementation will become terribly complex.
38
// And I mean terribly.
39
Thread JavaDoc thread = new Thread JavaDoc(Thread.currentThread().getThreadGroup(), new Runnable JavaDoc()
40       {
41          public void run()
42          {
43             try
44             {
45                synchronized (MultiWorkerThread.this)
46                {
47                   runners.add(Thread.currentThread());
48                }
49
50                runTask(task);
51             }
52             finally
53             {
54                synchronized (MultiWorkerThread.this)
55                {
56                   runners.remove(Thread.currentThread());
57                }
58             }
59          }
60       }, getThreadName());
61       thread.setDaemon(true);
62       thread.start();
63       if (debug) System.out.println("Started WorkerThread " + thread);
64    }
65
66    public boolean isWorkerThread()
67    {
68       synchronized (this)
69       {
70          return runners.contains(Thread.currentThread());
71       }
72    }
73
74    boolean hasPendingTasks()
75    {
76       synchronized (this)
77       {
78          return super.hasPendingTasks() || runners.size() > 0;
79       }
80    }
81 }
82
Popular Tags