You could something like the following:
import java.util.concurrent.* ;
ExecutorService svc = Executors.newFixedThreadPool( 1 ) ;
svc.submit( new Runnable() {
public void run() {
// Do long running task
}
} ) ;
svc.shutdown() ;
svc.awaitTermination( 300, TimeUnit.SECONDS ) ;
Javadocs for ExecutorService are here
[edit]
I should probably note however that depending on what your long running task is doing, it may not be possible to force it to stop running
[edit2] the submit method returns a Future
object, which you can then call get
on with a timeout. This get
call will block until a result is ready, or if the timeout is reached throw a TimeoutException. In this way, you can get a result back from your long running task if that is what you wanted