java - 执行器服务invokeAll

标签 java multithreading executorservice

我对可调用界面相当陌生。我有一些代码目前无法编译,只是需要一些帮助来了解原因......

public List<String> getNonPingableRegisters (Collection<RegisterReplicationSynchTime> nonReplicatingRegisters) throws IOException {

    int nThreads = 15;
    final ExecutorService es = Executors.newFixedThreadPool(nThreads);

    Collection<Callable<PingTask>> pingTasks = new ArrayList<Callable<PingTask>>(nonReplicatingRegisters.size());
    for (RegisterReplicationSynchTime nonReplicatingRegister : nonReplicatingRegisters) {
        pingTasks.add(new PingTask(nonReplicatingRegister.getRegisterName()));
    }

    List<Future<String>> taskResults = es.invokeAll(pingTasks);
    List<String> results = new ArrayList<String>();

    for (Future<String> taskResult : taskResults) {
        try {
            String output = taskResult.get();
            if (StringUtils.isNotEmpty(output) ) {
                results.add(output);
            }
        } catch (InterruptedException e) {
            // handle accordingly
        } catch (ExecutionException e) {
            // handle accordingly          
        }
    }
    return results;
}

PingTask 在哪里...

public class PingTask implements Callable<String> {

    private String hostname = null;

    public PingTask(String hostname) {
        this.hostname = hostname;
    }

        public String call() {
            Socket socket = null;
            boolean reachable = false;  
            try {                           
                socket = new Socket();
                socket.connect(new InetSocketAddress(hostname, 139), 1000); //1 sec timeout                     
                reachable = true;
                socket.close();
            } catch (IOException e) {

            }
            finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {

                    }
                }
            }       
            return (reachable ? "" : hostname);
        }

    }

编译错误位于...

List<Future<String>> taskResults = es.invokeAll(pingTasks);

类型 Collection> 中的方法 add(Callable) 不适用于参数 (PingTask) StoreReplicationSynchtimeManagerImpl.java

不确定我需要在这里做什么来调用invokeAll。希望得到一些帮助。

谢谢

最佳答案

错误不在该行。 它位于:

pingTasks.add(new PingTask(nonReplicatingRegister.getRegisterName()));

您的集合是 Callable 的,因为您的 PingTask 类实现了 Callable。将集合更改为:

Collection<Callable<String>>

关于java - 执行器服务invokeAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35284282/

相关文章:

java - File Writer 覆盖之前写入的 Java

c - 服务器不会为每个新客户端(套接字)分配线程

java - 如何继续向执行者提交任务

c# - 在循环中创建新线程

android - 为什么 AsyncTask 运行在应用程序的主线程中?

java - 停止提交给 ExecutorService 的 Runnable

java - 具有固定大小线程池的 ExecutorService - 如何阻止添加更多任务,直到池大小有空间

java - 我如何获得两个日期之间的天数,包括时间?

java - key=value 的正则表达式是什么,以逗号分隔?

java - hibernate 构造函数