I think that this is what you want:
private final Thread thisThread = Thread.current();
private final int timeToRun = 120000; // 2 minutes;
new Thread(new Runnable() {
public void run() {
sleep(timeToRun);
thisThread.interrupt();
}).start();
while (!Thread.interrupted()) {
// do something interesting.
}
This avoids doing repeated syscalls to get the system clock value (which can be rather expensive) and polls the current thread's interrupted
flag instead (much cheaper).
EDIT
There is actually no safe alternative to polling the clock or polling a flag. In theory, you could modify the above fragment to call the deprecated Thread.stop()
method instead of Thread.interrupt()
.
(I do NOT recommend using Thread.stop()
and friends. They are flawed, and dangerous to use. I'm just posing this as a theoretical alternative.)
EDIT 2
Just to point out that using Thread.interrupt()
has the advantages over setting a shared flag:
Thread.interrupt() will cause certain blocking I/O and synchronization methods to unblock and throw a checked exception. Updating a shared flag won't do this.
Some third-party libraries also check the interrupt flag to see if they should stop what they are currently doing.
If your loop involves calls to other methods, etc, Thread.interrupt() means that you don't need to worry about those methods can access the flag ... if they need to.
EDIT 3
Just to add that sleep(N)
is not guaranteed to wake the sleeping thread up after exactly N
milliseconds. But under normal circumstances, it will be reasonably close.