KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > activedirectory > ThreadRunner


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program 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
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.activedirectory;
21
22 /**
23  * General purpose runner for Runnable tasks.
24  */

25 public final class ThreadRunner implements Runnable JavaDoc {
26     private final Thread JavaDoc runner;
27     private final Runnable JavaDoc runnable;
28     private final int sleepPeriod;
29     private boolean running;
30     
31     /**
32      * Constructor
33      * @param name
34      * @param runnable
35      * @param sleepPeriod
36      */

37     public ThreadRunner(String JavaDoc name, Runnable JavaDoc runnable, int sleepPeriod) {
38         this.runner = new Thread JavaDoc(this, name);
39         this.runner.setPriority(Thread.NORM_PRIORITY);
40         this.runnable = runnable;
41         this.sleepPeriod = sleepPeriod;
42     }
43     
44     private synchronized boolean isRunning() {
45         return running;
46     }
47     
48     private synchronized void setRunning(boolean running) {
49         this.running = running;
50     }
51     
52     /**
53      * Causes this runner to begin execution
54      * <p>
55      * @exception IllegalThreadStateException if the runner was already started.
56      */

57     public void start() {
58         if(isRunning()) {
59             throw new IllegalStateException JavaDoc("ThreadRunner is already running.");
60         }
61         setRunning(true);
62         runner.start();
63     }
64     
65     /**
66      * Asks the runner to stop execution. This will interrupt
67      * the runner if sleeping or trying to end the current job.
68      */

69     public void stop() {
70         setRunning(false);
71         runner.interrupt();
72     }
73     
74     public void run() {
75         while (isRunning()) {
76             runnable.run();
77             sleep();
78         }
79     }
80     
81     private void sleep() {
82         try {
83             Thread.sleep(sleepPeriod);
84         } catch (InterruptedException JavaDoc e) {
85             // ignore
86
}
87     }
88 }
Free Books   Free Magazines  
Popular Tags