Possible Duplicate:
How to timeout a thread
stop a thread in java after a given time - doesn't work
(some kind of thread)that can monitor time taken by a particular task, so that if time reaches to a particular limit, it retries it
Possible Duplicate:
How to timeout a thread
stop a thread in java after a given time - doesn't work
(some kind of thread)that can monitor time taken by a particular task, so that if time reaches to a particular limit, it retries it
Try it this way....
1. Use CountDownLatch
from java.util.concurrent.
2. CountDownLatch cdt = new CountDownLatch(10);
This will do your 10 task and everytime a task is done the count goes down by 1.
Use countDown()
method to decrement the count when a task is done.
Use await()
method to allow the execution of flow after 10 tasks are done.
3. Run another thread which monitors the time taken by CountDownLatch
to complete the
tasks.
4. Suppose the time is exceeding your desired time, then Re-initialize the CountDownLatch
If you only need a very rough estimate you could create a thread, put it to sleep for however long you need to, and then check if you need to restart your task. For example, you could create a thread whose run() command has a body like this:
Thread.sleep(5000); //5 seconds
while ( needToRestart() )
{
restart();
Thread.sleep(5000);
}
This will check if your task needs to be restarted every 5 seconds, and so if necessary. It's important to note that Thread.sleep is not accurate for timing purposes, but this is a cheap solution if the exact amount of time is not important.
If you define a starttime property for your task. You can always start a thread and in the run() method it will monitor your task. In the sense it will measure the currentTime - startTime(available with task object) and check if the difference has reached the threshhold.