如何在java中为文档对象设置解析持续时间限制

时间:2011-06-13 13:35:19

标签: java jtidy

我在java中使用Jtidy解析器。这是我的代码......

  URL url = new URL("www.yahoo.com");
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  InputStream in = conn.getInputStream();
  Tidy tidy = new Tidy();
  Document doc = tidy.parseDOM(in, null);

当我来到这个语句Document doc = tidy.parseDOM(in, null);时,解析页面需要花费太多时间,所以我想设置文档对象的时间限制。请帮帮我,如何设定时间。

1 个答案:

答案 0 :(得分:3)

您可以使用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<Document> task = new Callable<Document>() {
    public Document call() throws Exception {
        return tidy.parseDOM(in, null);
    }
};
Future<Document> future = service.submit(task);
// Future.get() offers a timed version that may throw a TimeoutException
Document doc = future.get(10, TimeUnit.SECONDS);