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

发布于 2024-11-15 05:09:32 字数 389 浏览 6 评论 0原文

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

I am using Jtidy parser in java.Here is my code...

  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);

when I come to this statement Document doc = tidy.parseDOM(in, null);,it is taking too much time to parse the page, so I want to set the time limit to document object. Please help me, how to set time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黑白记忆 2024-11-22 05:09:32

您可以使用 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);

You could use the java.util.Executors framework and submit a time-limited task to it.

Here's some code that demonstrates this:

// 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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文