Java ExecutorService-如何在可运行/可调用和可重用中设置值

Java ExecutorService-如何在可运行/可调用和可重用中设置值,java,multithreading,concurrency,Java,Multithreading,Concurrency,我想使用ExecutorService运行一系列相同的可运行/可调用任务。我搜索了一个教程或示例,但没有涉及实际设置现有可运行/可调用对象的值,然后使用submit将该对象发送回ExecutorService 基本上,我想做的是: 获取服务器列表。 遍历服务器列表,调用InetAddress.getByNamehost以获取每个主机上的数据。 将数据收集到服务器bean中,以便存储在数据库中。 所以,现在,有10000多台服务器,这需要永远的时间。因此,我的想法是使用ExecutorServic

我想使用ExecutorService运行一系列相同的可运行/可调用任务。我搜索了一个教程或示例,但没有涉及实际设置现有可运行/可调用对象的值,然后使用submit将该对象发送回ExecutorService

基本上,我想做的是:

获取服务器列表。 遍历服务器列表,调用InetAddress.getByNamehost以获取每个主机上的数据。 将数据收集到服务器bean中,以便存储在数据库中。 所以,现在,有10000多台服务器,这需要永远的时间。因此,我的想法是使用ExecutorService来管理线程池。我似乎不知道如何检测一个线程何时完成,以便获取数据。然后我需要获取列表中的下一个服务器,将其放入任务中,然后提交回ExecutorService

也就是说,到目前为止我读到的内容似乎指向以下内容:ExecutorService、submit、Callable、Future

因此,作为一个psuedo过程:

获取服务器列表。 使用numThreads设置ExecutorService线程数 迭代numThreads并创建numThreads WorkerTask对象。 将WorkerTask提交给ExecutorService进行处理。 检测WorkerTask何时完成,获取可调用的未来结果。 获取下一个服务器。
将服务器值设置到WorkerTask中我认为在这种情况下最好的方法是为每个服务器创建一个任务,因为它们将由pull中的线程执行,然后使用tge future对象检索任务返回的服务器信息。

可以做到这一点。我不明白你说的“获取结果”是什么意思,在哪里使用它,为什么不在同一个可运行实例中执行数据库保存?另外,调用ExecutorServiceshutdown只意味着executor服务将不会接收任何其他要执行的任务,并将执行挂起的任务。是。一旦我用IP查找巩固了这个模式,我计划使用该模式来处理数以百万行计的性能数据。当这种情况发生时,我将把SQL数据库更新代码放在worker任务中。
public List<ServerBean> lookupHostIps ( List<ServerBean> theServerList ) {
    //ServerBean                      serverDto   = null;
    ServerBean                      ipDto       = null;
    List<ServerBean>                theResults  = new ArrayList<ServerBean>();
    List<HostLookupWorker>          theWorkers  = new ArrayList<HostLookupWorker>( getNumberThreads() );
    List<Future<HostLookupWorker>>  theFutures  = new ArrayList<Future<HostLookupWorker>>( getNumberThreads() );

    ExecutorService executor = Executors.newFixedThreadPool ( getNumberThreads() );

    // WORKERS : Create the workers...prime them with a server
    // bean...
    // 
    for (int j = 0; j < getNumberThreads(); j++) {
    //for (int j = 0; j < theServerList.size(); j++) {
        theWorkers.add ( new HostLookupWorker( theServerList.get(j) ) );
        Future<HostLookupWorker> theFuture = executor.submit ( theWorkers.get ( j ) );
        theFutures.add ( j, theFuture );
    }

    int     lloopItems = getNumberThreads();     /* loops thru all servers   */
    //int     lloopThreads = 0;   /* loops thru threads       */
    int     lidxThread = 0;     /* what thread is ready     */
    //int     lidxFuture = 0;     /* what future is ready     */
    boolean lblnNext = false;   /* is a thread done/ready   */
    int lidxWorkers = 0;        /* tracks the futures       */
    while ( lloopItems < theServerList.size() ) {
        // READY : Is one of the threads ready for more work?
        if ( lblnNext ) {
            // VALUE : Grab the thread by index and set the next
            // server value.
            theWorkers.get ( lidxThread ).setBean ( theServerList.get(lloopItems) );
            getLog().debug ( "Thread [" + lidxThread + "] Assigned Host ["+theServerList.get(lloopItems).getServerName ()+"] " );
            // FUTURE : Package a new Future<HostLookupWorker> 
            // and submit it to the thread pool.
            Future<HostLookupWorker> theFuture = executor.submit ( theWorkers.get ( lidxThread ) );
            theFutures.add ( lidxThread, theFuture );
            lblnNext = false;   /* reset to allow for another thread    */
            lloopItems++;       /* increment the main loop counter       */
        }

        while ( !(lblnNext) ) {
            try { 
                if ( theFutures.get(lidxWorkers).get() != null ) {
                    // GET THE STUFF : Grab the results from the Future...
                    HostLookupWorker    ltheItem = theFutures.get(lidxWorkers).get();
                    if ( ltheItem.getValue () != null ) { 
                        if (!ltheItem.getValue ().contains("Cannot find host")){
                            ipDto = new ServerBean ();
                            ipDto.setServerId   ( ltheItem.getBean ().getServerId()   );
                            ipDto.setServerName ( ltheItem.getBean ().getServerName() );
                            ipDto.setIpAddress  ( ltheItem.getValue ()      );

                            theResults.add(ipDto);
                        }
                        lidxThread = lidxWorkers;   /* this thread is ready for more work   */
                        lblnNext = true;            /* flag the upper condition to assign new work  */
                        getLog().debug ( "Thread [" + lidxThread + "] Host ["+ltheItem.getHost ()+"] has IP ["+ltheItem.getValue()+"]" );
                    }
                }
                else { 
                    getLog().debug ( "Thread [" + lidxThread + "] NULL" );
                }

                lidxWorkers++;  /* next worker/future   */

                if ( lidxWorkers >= getNumberThreads() ) {
                    lidxWorkers = 0;
                } 

            } 
            catch(ExecutionException e){  
                getLog().error ( e );
            }
            catch(InterruptedException e){
                getLog().error ( e );
            }

        }
    }

    executor.shutdown ();

    return theResults;
}
import java.net.*;
import java.util.concurrent.Callable;

import com.lmig.cdbatch.dto.ServerBean;

public class HostLookupWorker implements Callable {

    private InetAddress node = null;
    private String      value = null;
    private boolean     busy = false;
    private ServerBean  bean    = null;

    public  HostLookupWorker () {
        this.busy = false;
    }

//    public  HostLookupWorker ( String theHost ) {
//        this.busy = false;
//        this.host = theHost;
//    }

    public  HostLookupWorker ( ServerBean theItem ) {
        this.busy = false;
        this.bean = theItem;
        //this.host = theItem.getServerName ().trim ();
    }

    public String lookup ( String host ) {

        if ( host != null ) { 
            // get the bytes of the IP address
            try {
                this.node = InetAddress.getByName ( host );
            } 
            catch ( UnknownHostException ex ) {
                this.value = "Not Found [" + getHost() + "]";
                return "Not Found [" + host + "]";
            }

            if ( isHostname(host) ) {
                getBean().setIpAddress ( node.getHostAddress() );
                return node.getHostAddress();
            } 
            else { // this is an IP address
                //return node.getHostName();
                return host;
            }
        }
        return host;

    } // end lookup

    public boolean isHostname(String host) {

        // Is this an IPv6 address?
        if (host.indexOf(':') != -1)
            return false;

        char[] ca = host.toCharArray();
        // if we see a character that is neither a digit nor a period
        // then host is probably a hostname
        for (int i = 0; i < ca.length; i++) {
            if (!Character.isDigit(ca[i])) {
                if (ca[i] != '.')
                    return true;
            }
        }

        // Everything was either a digit or a period
        // so host looks like an IPv4 address in dotted quad format
        return false;
    } // end isHostName

//    public void run() {
//        value = lookup ( getHost() );
//        
//    }

    public Object call() throws Exception {
        Thread.sleep ( 10000 );
        this.busy = true;
        this.value = lookup ( getHost() );
        this.busy = false;
        return this;
    }

    public String getHost() {
        return getBean().getServerName ().trim ();
    }

    public void setHost(String host) {
        getBean().setServerName ( host.trim () );
    }

    public InetAddress getNode() {
        return node;
    }

    public void setNode(InetAddress node) {
        this.node = node;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public boolean isBusy() {
        return busy;
    }

    public void setBusy(boolean busy) {
        this.busy = busy;
    }

    public ServerBean getBean() {
        return bean;
    }

    public void setBean(ServerBean bean) {
        this.bean = bean;
    }

}