0

我有一个在套接字连接上创建新线程的应用程序。我想将此线程中的 Callable 提交给 ExecutorService。Callable 需要通过命令行参数执行程序,所以我不想通过连接线程执行此操作。

问题是,我不知道如何将 Callable 提交给具有设定线程数的 ExecutorService。

我曾考虑使用单例执行此操作并编写提交方法以将我的 Callable 提交给 ExecutorService 实例,但不熟悉 api,我不确定这是否明智。

非常感谢任何帮助,谢谢。

4

3 回答 3

11

I would try

 static final ExecutorService service = Executors.newFixedThreadPool(4);

 Callable call = 
 service.submit(call);
于 2012-04-24T14:55:48.727 回答
3

这是我在网上找到的有关您的问题的一些代码:

public class CallableExample {

  public static class WordLengthCallable
        implements Callable {
    private String word;
    public WordLengthCallable(String word) {
      this.word = word;
    }
    public Integer call() {
      return Integer.valueOf(word.length());
    }
  }

  public static void main(String args[]) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    Set<Future<Integer>> set = new HashSet<Future≶Integer>>();
    for (String word: args) {
      Callable<Integer> callable = new WordLengthCallable(word);
      Future<Integer> future = pool.submit(callable);
      set.add(future);
    }
    int sum = 0;
    for (Future<Integer> future : set) {
      sum += future.get();
    }
    System.out.printf("The sum of lengths is %s%n", sum);
    System.exit(sum);
  }
}
于 2012-04-24T14:54:38.860 回答
2

There is method submit():

ExecutorService service = Executors.(get the one here you like most)();
Callable<Something> callable = (your Callable here);
Future<AnotherSomething> result = service.submit(callable);

Please note than when using executor service, you have no control over when the task actually starts.

于 2012-04-24T15:06:22.553 回答