[英]how to set parse duration limit to document object in java
我在 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);
,解析頁面的時間太長,所以我想為文檔object設置時間限制。 請幫助我,如何設置時間。
您可以使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.