2012-04-24 25 views
0

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

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

我曾经考虑过用singleton编写一个提交方法来将我的Callable提交给ExecutorService实例,但对api不熟悉,我不确定这是否合理。

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

回答

10

我会尝试

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

Callable call = 
service.submit(call); 
+0

感谢彼得,这符合我的需求。 – kidloco 2012-04-24 15:31:37

2

下面是一些代码,我在网上找你的问题:

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

我会使用期货清单,以便以可预测的顺序收集其结果。 – 2012-04-24 14:56:43

2

还有就是方法提交():

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

请注意时相比,使用执行器服务,您无法控制任务实际开始的时间。

+0

为什么*另一个*的未来而不是东西的未来? – javadba 2015-08-09 16:52:37

相关问题