java 如何从线程向 ExecutorService 提交 Callable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10300426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:27:08  来源:igfitidea点击:

How to submit a Callable to an ExecutorService from a thread

javaconcurrency

提问by kidloco

I have an application which creates a new thread on a socket connection. I would like to submit a Callable from this thread to an ExecutorService. The Callable needs to execute a program via a command line argument, so I don't want to do this via the connection thread.

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

The problem is, I don't know how to submit the Callable to an ExecutorService which has a set thread count.

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

I had considered doing this with a singleton and writing a submit method to submit my Callable to the ExecutorService instance but being unfamiliar with the api, I wasn't sure if this was sensible.

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

Any help is greatly appreciated, Thanks.

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

回答by Peter Lawrey

I would try

我会尝试

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

 Callable call = 
 service.submit(call);

回答by Zhivko Draganov

Here is some code I find online about your problem :

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

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);
  }
}

回答by Jakub Zaverka

There is method submit():

有方法 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.

请注意,在使用 executor 服务时,您无法控制任务实际启动的时间。