3

私はJavaでJtidyパーサーを使用しています.Hereは私のコードです...

  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 に答える