01: /*
02: * CoadunationLib: The coaduntion implementation library.
03: * Copyright (C) 2006 Rift IT Contracting
04: *
05: * This library is free software; you can redistribute it and/or
06: * modify it under the terms of the GNU Lesser General Public
07: * License as published by the Free Software Foundation; either
08: * version 2.1 of the License, or (at your option) any later version.
09: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library; if not, write to the Free Software
17: * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18: *
19: * ThreadStateMonitor.java
20: *
21: * This object is responsible for monitoring the state of a thread.
22: */
23:
24: package com.rift.coad.lib.thread;
25:
26: /**
27: * This object is responsible for monitoring the state of a thread.
28: *
29: * @author Brett Chaldecott
30: */
31: public class ThreadStateMonitor {
32:
33: // the private member variables
34: private boolean terminated = false;
35: private long delay = 0;
36:
37: /**
38: * Creates a new instance of ThreadStateMonitor
39: */
40: public ThreadStateMonitor() {
41: }
42:
43: /**
44: * The constructor that sets the delay time for the thread state monitor.
45: *
46: * @param delay The length of time the thread should what before continuing
47: * to the next processing iteration.
48: */
49: public ThreadStateMonitor(long delay) {
50: this .delay = delay;
51: }
52:
53: /**
54: * This method returns true if this object is terminated and false if it
55: * is not.
56: *
57: * @return TRUE if terminated, FALSE if not.
58: */
59: public synchronized boolean isTerminated() {
60: return terminated;
61: }
62:
63: /**
64: * This method sets the terminated flag to true and notifies waiting threads
65: * of this fact.
66: *
67: * @param broadCast Set to true if there can be more than one thread blocking.
68: */
69: public synchronized void terminate(boolean broadCast) {
70: terminated = true;
71: if (broadCast) {
72: notifyAll();
73: } else {
74: notify();
75: }
76: }
77:
78: /**
79: * This method will get called to monitor the state of the thread.
80: */
81: public synchronized void monitor() {
82: try {
83: if (terminated) {
84: return;
85: }
86: if (delay > 0) {
87: wait(delay);
88: } else {
89: wait();
90: }
91: } catch (Exception ex) {
92: // ignore
93: }
94: }
95: }
|