Reputation: 31
I want to run a thread for some fixed amount of time.
If it is not completed within that time, I want to either kill it, throw some exception, or handle it in some way. How can this be done?
Upvotes: 3
Views: 206
Reputation: 15320
You should use an ExecutorService
:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new Task());
try {
System.out.println("Started");
Integer retval = future.get(10, TimeUnit.SECONDS)); // you can choose your desired time here
System.out.println("Finished");
} catch (TimeoutException e) {
future.cancel(true);
System.out.println("Timeout happened");
// handle termination here
}
executor.shutdownNow();
And your Callable
can look something like this:
class Task implements Callable<Integer> {
@Override
public String call() throws Exception {
// some code here
return 0;
}
}
Upvotes: 3