001: /* JFox, the OpenSource J2EE Application Server
002: *
003: * Copyright (C) 2002 huihoo.org
004: * Distributable under GNU LGPL license
005: * See the GNU Lesser General Public License for more details.
006: */
007:
008: package org.huihoo.jfox.pool.thread;
009:
010: import org.huihoo.jfox.pool.ObjectPool;
011:
012: /**
013: *
014: * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
015: */
016:
017: public class WorkerThread extends Thread implements
018: ThreadPoolableObject {
019: private ThreadTask task = null;
020: private volatile boolean running = false;
021: private static volatile long threadId = 0L;
022: private volatile boolean waiting = false;
023:
024: public WorkerThread() {
025: super ("WorkerThread: " + threadId++);
026: // System.out.println("make WorkerThread: " + (threadId -1));
027: running = true;
028: this .start();
029: }
030:
031: public void run() {
032: do {
033: if (!running)
034: break;
035: try {
036: // System.out.println("WorkerThread.run " + this.getName() + ", waiting " + waiting);
037: synchronized (this ) {
038: waiting = true;
039: // System.out.println("WorkerThread.run " + this.getName() + ", waiting " + waiting);
040: wait();
041: // System.out.println("WorkerThread.run " + this.getName() + " have wakenup");
042: }
043: } catch (InterruptedException e) {
044: e.printStackTrace();
045: waiting = false;
046: if (!running || task == null)
047: break;
048: }
049:
050: // System.out.println("WorkerThread.wakeup " + this.getName());
051:
052: waiting = false; // have wakeup
053: if (task == null)
054: break; // maybe wakeup by discard() method
055: try {
056: task.getTask().run();
057: } catch (Throwable throwable) {
058: // System.err.println("WorkerThread:Ignored Exception: " + throwable.toString());
059: } finally {
060: // must restore the WorkThread to object pool
061: synchronized (this ) {
062: ObjectPool pool = task.getPool();
063: synchronized (pool) {
064: pool.restoreObject(this );
065: }
066: }
067: }
068:
069: } while (true);
070: }
071:
072: public void activate() throws Exception {
073: // System.out.println("WorkerThread.activate");
074: running = true;
075: }
076:
077: public void passivate() throws Exception {
078: // System.out.println("WorkerThread.passivate");
079: task = null;
080: }
081:
082: public void destory() throws Exception {
083: notifyAll();
084: }
085:
086: public void setTask(ThreadTask task) {
087: // System.out.println("WorkerThread.setTask" + getName() + " waiting " + waiting + ", running " + running );
088: if (waiting == true) {
089: this .task = task;
090: synchronized (this ) {
091: System.out.println("WorkerThread.setTask.notifyAll "
092: + getName());
093: try {
094: sleep(10L);
095: } catch (InterruptedException e) {
096: e.printStackTrace();
097: }
098: notifyAll();
099: }
100: }
101: }
102:
103: public void discard() {
104: running = false;
105: synchronized (this) {
106: notifyAll();
107: }
108: task.getPool().removeObject(this);
109: }
110:
111: }
|