gpt4 book ai didi

Java 线程 : Futures only using results from first and last thread

转载 作者:行者123 更新时间:2023-11-29 05:45:39 24 4
gpt4 key购买 nike

我有一个简单的实用程序,它可以对一组节点执行 ping 操作,并将字符串的 ArrayList 返回给 future 的对象以输出到文件中。该程序应一直运行,直到被用户终止。

future 似乎没有收到结果(或至少将它们传递给方法以输出到文件)。无论我同时运行的线程数(总是少于 100,由输入文件确定),我都只输出第一个和最后一个初始化线程的结果。

作为健全性检查,我创建了一个全局变量,每个线程在关闭并将其结果返回给 Future 对象之前将其结果发送到其中。此变量已由所有线程正确更新。

有没有人知道为什么 Future 似乎没有从线程中收到我的所有结果?

public class PingUtility{
public static ExecutorService pool = Executors.newFixedThreadPool(100);
static Future<ArrayList<String>> future;

public static void main(String[] args) throws Exception {

Timer timer = new Timer();
TimerTask task = new TimerTask(){
public void run(){
//Creates a pool of threads to be executed
ArrayList<String[]> nodes = new ArrayList<String[]>()
future = pool.submit(new PingNode(nodes));
}
}
};

timer.scheduleAtFixedRate(task, 0, interval);

while(true){
try{
ArrayList<String[]> tempOutputArray = future.get();
Iterator<String[]> it = tempOutputArray.iterator();
while(it.hasNext()) appendFile(it.next());
tempOutputArray.clear();
}catch(Exception nullException){
//Do nothing
}
}
}

最佳答案

你的问题是你正在修改 future 静态字段没有你的计时器任务线程中的同步并在主线程中读取它。您需要在修改读取它时对其进行同步,或者使用其他机制在线程之间共享信息。

我建议从 static 字段切换到 LinkedBlockingQueue 作为将信息从 PingNode 调用发送到 的更好方法code>appendFile(...) 方法。这样就无需自己进行同步,并防止出现多个计时器任务将启动并在消费者可以从它们get()之前覆盖future的竞争条件。也许是这样的:

 BlockingQueue<String[]> queue = new LinkedBlockingQueue<String[]>();
...

// inside of run, producer passes the queue into the PingNode
public void run() {
pool.submit(new PingNode(queue));
}

// consumer
while (true) {
String[] array = queue.take();
...
}

这不会影响您在完成后如何停止线程。如果计时器任务被终止,实体可以向队列中添加一个终止对象以停止主循环。

关于Java 线程 : Futures only using results from first and last thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15950551/

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