gpt4 book ai didi

java - ExecutorService 未接来电

转载 作者:行者123 更新时间:2023-12-02 06:14:21 26 4
gpt4 key购买 nike

我的 ExecutorService 有问题,它不执行所有调用。

public class MainClass {

public static void main(String[] args) throws IOException, InvalidConnection, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();

XMLUrlService xmlUrlService = new XMLUrlService();
LinkedBlockingQueue<String> linkedBlockingQueue = xmlUrlService.getAllXMLUrls();

System.out.println(linkedBlockingQueue.size());
for (int i = 0; i < linkedBlockingQueue.size(); i++) {

executor.execute(new XMLParser(linkedBlockingQueue));
}

executor.shutdown();
}

}

XMLUrlService 类返回 URL 列表,然后执行连接。

XMLPaser 是一个负责与给定 URL 建立连接的类。


public class XMLParser implements Runnable {


private LinkedBlockingQueue queue;

public XMLParser(LinkedBlockingQueue queue) {
this.queue = queue;
}

public XMLParser(){}

public void getRates(String data) throws IOException, XMLStreamException, InvalidConnection {

URL url = new URL(data);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();

inputStream.close();
connection.disconnect();
}


public void run() {
try {
String data = (String) queue.take();
getRates(data);

} catch (InterruptedException | IOException ex) {
//Handle exception
} catch (InvalidConnection invalidConnection) {
invalidConnection.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
}

我的阻塞队列包含250个不同的url地址,但是executorservice执行随机数量的调用(250只是要测试的元素的随机数量)。我认为当我从队列中取出项目时,我可以省略一些,但我不确定。

最佳答案

您应该更改三件事:

执行任务的方式
您正在以一种非常奇怪的方式执行任务。不要传递linkedBlockingQueue,而是传递String,如下所示:

System.out.println(linkedBlockingQueue.size());
for (int i = 0; i < linkedBlockingQueue.size(); i++) {
String url = linkedBlockingQueue.remove()
executor.execute(new XMLParser(url));
}

处理异常的方式
不要吞下异常 - 最简单的方法是使用 Callable 来获取 Future ,以便您稍后可以检查任务发生了什么:

    ExecutorService executor = Executors.newCachedThreadPool();

LinkedBlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<String>();

System.out.println(linkedBlockingQueue.size());

List<Future<Void>> result = linkedBlockingQueue.stream().map(
url -> executor.submit(new XMLParser(url))
).collect(Collectors.toList());

for (Future<Void> future : result) {
try {
future.get();
} catch (Exception e) {
System.out.println("Something happened:" + e);
}
}

executor.shutdown();

等待执行关闭执行器后,等待所有任务完成。

executor.shutdown();
executor.awaitTermination(10, TimeUnit.HOURS);

关于java - ExecutorService 未接来电,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55881246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com