KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > concurrent > StoppableThread


1 /**
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.util.concurrent;
5
6 /**
7  * This class isn't very exciting, nor is it best (or only) way to implement a (safe) stoppable thread. It is useful to
8  * subclass StoppableThread if need to support stop functionality and you don't want to assume that it's okay to just
9  * interrupt() the thread at any given moment. In my opinion, if the code you're running in the thread isn't entirely in
10  * your control, you probably don't want to randomly interrupt it. For threads that spend most of their time blocking on
11  * something, simply use a timeout and periodically check stopRequested() to see if it is time to stop. <br>
12  * <br>
13  * README: You have to actually check stopRequested() someplace in your run() method for this thread to be "stoppable".
14  */

15 public class StoppableThread extends Thread JavaDoc implements LifeCycleState {
16
17   private volatile boolean stopRequested = false;
18
19   public StoppableThread() {
20     super();
21   }
22
23   public StoppableThread(Runnable JavaDoc target) {
24     super(target);
25   }
26
27   public StoppableThread(String JavaDoc name) {
28     super(name);
29   }
30
31   public StoppableThread(ThreadGroup JavaDoc group, Runnable JavaDoc target) {
32     super(group, target);
33   }
34
35   public StoppableThread(Runnable JavaDoc target, String JavaDoc name) {
36     super(target, name);
37   }
38
39   public StoppableThread(ThreadGroup JavaDoc group, String JavaDoc name) {
40     super(group, name);
41   }
42
43   public StoppableThread(ThreadGroup JavaDoc group, Runnable JavaDoc target, String JavaDoc name) {
44     super(group, target, name);
45   }
46
47   public StoppableThread(ThreadGroup JavaDoc group, Runnable JavaDoc target, String JavaDoc name, long stackSize) {
48     super(group, target, name, stackSize);
49   }
50
51   public boolean isStopRequested() {
52     return stopRequested;
53   }
54
55   public void requestStop() {
56     this.stopRequested = true;
57   }
58
59   public boolean stopAndWait(long timeout) {
60     requestStop();
61     try {
62       join(timeout);
63     } catch (InterruptedException JavaDoc e) {
64       //
65
}
66     return !isAlive();
67   }
68
69 }
70
Popular Tags