class ThreadMonitor
extends java.lang.Object
implements java.lang.Runnable
This works by sleeping until the specified timeout amount and then
interrupting the thread being monitored. If the thread being monitored
completes its work before being interrupted, it should interrupt()
the monitor thread.
long timeoutInMillis = 1000; try { Thread monitor = ThreadMonitor.start(timeoutInMillis); // do some work here ThreadMonitor.stop(monitor); } catch (InterruptedException e) { // timed amount was reached }
Modifier and Type | Field and Description |
---|---|
private java.lang.Thread |
thread |
private long |
timeout |
Modifier | Constructor and Description |
---|---|
private |
ThreadMonitor(java.lang.Thread thread,
long timeout)
Construct and new monitor.
|
Modifier and Type | Method and Description |
---|---|
void |
run()
Sleep until the specified timeout amount and then
interrupt the thread being monitored.
|
private static void |
sleep(long ms)
Sleep for a guaranteed minimum number of milliseconds unless interrupted.
|
static java.lang.Thread |
start(long timeout)
Start monitoring the current thread.
|
static java.lang.Thread |
start(java.lang.Thread thread,
long timeout)
Start monitoring the specified thread.
|
static void |
stop(java.lang.Thread thread)
Stop monitoring the specified thread.
|
private ThreadMonitor(java.lang.Thread thread, long timeout)
thread
- The thread to monitortimeout
- The timeout amount in millisecondspublic static java.lang.Thread start(long timeout)
timeout
- The timeout amount in milliseconds
or no timeout if the value is zero or lessnull
if the timeout amount is not greater than zeropublic static java.lang.Thread start(java.lang.Thread thread, long timeout)
thread
- The thread The thread to monitortimeout
- The timeout amount in milliseconds
or no timeout if the value is zero or lessnull
if the timeout amount is not greater than zeropublic static void stop(java.lang.Thread thread)
thread
- The monitor thread, may be null
public void run()
run
in interface java.lang.Runnable
Runnable.run()
private static void sleep(long ms) throws java.lang.InterruptedException
ms
- the number of milliseconds to sleep forjava.lang.InterruptedException
- if interrupted