gpt4 book ai didi

java - 如何从Java中的多个线程获取和处理对象?如何创建 Future 的多个实例

转载 作者:行者123 更新时间:2023-11-29 05:50:02 25 4
gpt4 key购买 nike

我需要创建一堆到不同主机的 JMX 连接。我正在尝试并行创建这些连接。在这方面的表现比现在好多了。

我有方法将“主机和端口”条目的集合传递给该方法。将为每个条目创建一个连接。

现在我要提交这个创建连接到多线程的任务。但是我不知道如何返回并存储线程创建的连接对象。

代码是这样的,

ConnectionFactory.createConnections(collection of hostportEntries)

class ConnectionFactory{

public static CollectionOfConnections createConnections(ListOfHostPorts)
{

ExecutorService exec = Executors.newFixedThreadPool(4);

for(iterate over hostportEntries)
{
Future<Connection> future1 = exec.submit(new connCreator(HostPortEntry));

//Now here, connCreator is implementing Callable Interface and creating connection. and returning it. I'm taking reference of that Returned connection.
//But how will I take Multiple Connection objects returned by Multiple threads. I tried to create Future[] but OPTION like that doesn't seem to be there
// Can anybody help here?????

}

//if I succeed in getting the objects return then I'll store in one more collection and return those for further use of those connections.

}

最佳答案

看看 ThreadPool 的 invokeAll 方法 - 它接受 Callables 的集合并返回 Futures 的列表。

编辑:与简单地一次提交一个任务并将 Futures 放入您自己的列表相比,使用 invokeAll 的优势在于 invokeAll 只会在所有任务完成后返回,因此您不必一直检查所有的 future ,看看他们是否已经完成。

关于java - 如何从Java中的多个线程获取和处理对象?如何创建 Future 的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14265316/

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