In the code, the variable timer would specify the duration after which to end the while loop, 60 sec for example.
while(timer) {
//run
//terminate after 60 sec
}
In the code, the variable timer would specify the duration after which to end the while loop, 60 sec for example.
while(timer) {
//run
//terminate after 60 sec
}
you should try the new Java Executor Services. http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
With this you don't need to program the loop the time measuring by yourself.
If you can't go over your time limit (it's a hard limit) then a thread is your best bet. You can use a loop to terminate the thread once you get to the time threshold. Whatever is going on in that thread at the time can be interrupted, allowing calculations to stop almost instantly. Here is an example:
That will give you resolution to about 1/2 second. By polling more often in the while loop, you can get that down.
Your runnable's run would look something like this:
Update based on Dmitri's answer
Dmitri pointed out TimerTask, which would let you avoid the loop. You could just do the join call and the TimerTask you setup would take care of interrupting the thread. This would let you get more exact resolution without having to poll in a loop.
Depends on what the while loop is doing. If there is a chance that it will block for a long time, use
TimerTask
to schedule a task to set astopExecution
flag, and also.interrupt()
your thread.With just a time condition in the loop, it could sit there forever waiting for input or a lock (then again, may not be a problem for you).