001: /**
002: * $Id: ReusableThread.java,v 1.5 2002/07/19 18:36:56 davechiu Exp $
003: * Copyright 2002 Sun Microsystems, Inc. All
004: * rights reserved. Use of this product is subject
005: * to license terms. Federal Acquisitions:
006: * Commercial Software -- Government Users
007: * Subject to Standard License Terms and
008: * Conditions.
009: *
010: * Sun, Sun Microsystems, the Sun logo, and Sun ONE
011: * are trademarks or registered trademarks of Sun Microsystems,
012: * Inc. in the United States and other countries.
013: */package com.sun.common.pool;
014:
015: import com.sun.common.util.LockWithMemory;
016:
017: public class ReusableThread implements Runnable, PartitionObject {
018: private ThreadPool _ownerPool;
019: private Thread _thread;
020: private boolean _running = true;
021: private LockWithMemory _begin = new LockWithMemory();
022: private LockWithMemory _end = new LockWithMemory();
023: private Runnable _runnable = null;
024: private boolean _executing = false;
025: private int _partition;
026: private boolean _reuse = true;
027:
028: ReusableThread(ThreadPool ownerPool) {
029: _ownerPool = ownerPool;
030: _thread = new Thread(this );
031: _thread.setDaemon(true);
032: _thread.start();
033: }
034:
035: void setReuseThread(boolean b) {
036: _reuse = b;
037: }
038:
039: public void setPartition(int partition) {
040: _partition = partition;
041: }
042:
043: public int getPartition() {
044: return _partition;
045: }
046:
047: void setRunnable(Runnable runnable) {
048: _runnable = runnable;
049: _executing = false;
050: }
051:
052: public void start() {
053: _begin.signal();
054: _executing = true;
055: }
056:
057: public void join() {
058: join(0, 0);
059: }
060:
061: public void join(long timeout) {
062: join(timeout, 0);
063: }
064:
065: public void join(long timeout, int nanos) {
066: if (_runnable != null) {
067: try {
068: _end.waitFor(timeout, nanos);
069: } catch (InterruptedException ie) {
070: //System.out.println("ReusableThread.join(), ie: "+ie);
071: }
072: }
073: }
074:
075: public boolean isAlive() {
076: return _executing;
077: }
078:
079: void finish() {
080: _running = false;
081: _begin.signal();
082: }
083:
084: public void run() {
085: try {
086: while (_running) {
087: try {
088: _begin.waitFor();
089: try {
090: if (_runnable != null) {
091: _runnable.run();
092: }
093: } catch (Throwable ex1) {
094: //System.out.println("ReusableThread.run(), ex1: "+ex1);
095: }
096: _running = _reuse;
097: _end.signal();
098: _executing = false;
099: _ownerPool.releaseThread(this );
100: } catch (Exception ex2) {
101: //System.out.println("ReusableThread.run(), ex2: "+ex2);
102: }
103: }
104: } catch (Exception ex3) {
105: //System.out.println("ReusableThread.run(), ex3: "+ex3);
106: }
107: }
108:
109: }
|