我想在一段固定的时间内运行一个帖子 如果它没有在那段时间内完成,我想杀死它,抛出一些异常,或以某种方式处理它。怎么办呢?
答案 0 :(得分:3)
您应该使用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();
您的Callable
看起来像这样:
class Task implements Callable<Integer> {
@Override
public String call() throws Exception {
// some code here
return 0;
}
}