3

我在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);时,解析页面花费了太多时间,所以我想为文档对象设置时间限制。请帮助我,如何设置时间。

4

1 回答 1

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);
于 2011-06-13T13:42:14.320 回答