您可以使用java.util.Executors框架并向其提交有时间限制的任务。
这里有一些代码可以证明这一点:
// Note that these variables must be declared final to be accessible to task
final InputStream in = conn.getInputStream();
final Tidy tidy = new Tidy();
ExecutorService service = Executors.newSingleThreadExecutor();
// Create an anonymous class that will be submitted to the service and returns your result
Callable task = new Callable() {
public Document call() throws Exception {
return tidy.parseDOM(in, null);
}
};
Future future = service.submit(task);
// Future.get() offers a timed version that may throw a TimeoutException
Document doc = future.get(10, TimeUnit.SECONDS);