具有不同返回类型的可变callables [英] Variable callables with different return types

查看:105
本文介绍了具有不同返回类型的可变callables的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我手头的问题是我的方法 one(),two(),three(),four()有不同的返回类型说, A,B,C,D 我需要生成可变数量的线程(每个方法一个,具体取决于用例。这意味着我想调用方法的子集一次。)现在,我使用 cachedThreadPool 来提交这些callables。下面的一些代码:

The problem I have in hand is that I methods one(), two(), three(), four() that have a different return types say, A, B, C, D and I need to spawn variable numbers of threads (one for each method depending on the use case. This means I would want to call a subset of methods at a time.) Now, am using the cachedThreadPool to submit these callables. Some code below:

public class Dispatcher {

  public void dispatch(List<MethodNames> methodNames) {
    //Now I am going to iterate through the list of methodNames
    //And submit each method to the `ExecutorService`
    for(MethodNames m : methodNames) {
      switch(m) {
        case ONE: //submit one()
                  //wait and get the future
                  Future<A> future = cachePool.submit(new Callable<A>() {
                    @Override
                    public A call() {
                      return one();
                    });
                  A response = future.get(); 
             break;
        ....
      }
    }
  }
}

public enum MethodNames {
  ONE, TWO, THREE, FOUR
}

//Example methods:
public A one() {
}

public B two() {
}

我的问题是如何做以上所有方法调用而不必等一个完成。另外,如何收集所有期货并等待它们完成,因为所有期货都有不同的通用类型 Future< A>,Future< B> 等我在case语句中调用 submit(),因此我无法访问返回的 Future< T> 在案例之外。现在我可以做一个 if,else 而不是 for 循环但是我想弄清楚是否有更好的方法来实现这一点。

My question is how do the above such that all the method calls are made without having to wait for one to finish. Also, how do I gather all the futures and wait for them to finish cause all the futures have a different generic type Future<A>, Future<B> etc. I make the call to submit() inside the case statement so I don't have the access to the returned Future<T> outside the case. Now I could do an if, else instead of the for loop but I am trying to figure out if there is a better way to achieve this.

推荐答案

我会这样做 -


  • 创建一个界面,假设

  • 有类 A B C D implements I

  • 使用枚举 valueOf 和对象覆盖删除案例陈述。

  • 使用多态并从所有方法返回 I

  • 以下是代码(不包括 A B C D )因为它们是纯类并且接口 - 没有做太多。

  • Create an interface, let's say I.
  • Have classes A, B, C and D implements I.
  • Use enums valueOf and object overriding to remove case statement.
  • Use polymorphism and return I from all the methods.
  • Below is the code (not including A, B, C, D, I) as they are plain class and interface - not doing much.

以下是代码:


Dispatcher.java

Dispatcher.java



package com.test.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class Dispatcher {

public void dispatch() throws InterruptedException, ExecutionException {
    Map<MethodNames, Future<I>> reponse = new HashMap<MethodNames, Future<I>>();
    ExecutorService cachePool = Executors.newCachedThreadPool();
    for (MethodNames methodNames : MethodNames.values()) {
        Future<I> future = cachePool.submit(methodNames.worker());
        reponse.put(methodNames, future);
    }
    cachePool.awaitTermination(5, TimeUnit.MINUTES);
    for(MethodNames key : reponse.keySet()) {
        I result = reponse.get(key).get();
        System.out.println("result :: " + result);
    }
}

public static void main(String[] args) throws InterruptedException, ExecutionException {
    new Dispatcher().dispatch();
}

}


MethodNames.java

MethodNames.java



package com.test.thread;

import java.util.concurrent.*;

public enum MethodNames {
ONE {
    @Override
    public Callable<I> worker() {
        return new Callable<I>() {
            @Override
            public I call() throws InterruptedException {
                System.out.println("Thread1");
                TimeUnit.SECONDS.sleep(30);
              return new A();
            }};
    }
},
TWO {
    @Override
    public Callable<I> worker() throws InterruptedException {
        return new Callable<I>() {
            @Override
            public I call() throws InterruptedException {
                System.out.println("Thread2");
                TimeUnit.SECONDS.sleep(30);
              return new B();
            }};
    }
},
THREE {
    @Override
    public Callable<I> worker() throws InterruptedException {
        return new Callable<I>() {
            @Override
            public I call() throws InterruptedException {
                System.out.println("Thread3");
                TimeUnit.SECONDS.sleep(30);
              return new C();
            }};
    }
},
FOUR {
    @Override
    public Callable<I> worker() throws InterruptedException {
        return new Callable<I>() {
            @Override
            public I call() throws InterruptedException {
                System.out.println("Thread");
                TimeUnit.SECONDS.sleep(30);
              return new D();
            }};
    }
};
public abstract Callable<I> worker() throws InterruptedException;

}

这篇关于具有不同返回类型的可变callables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆