[英]How to submit a Callable to an ExecutorService from a thread
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.
我想将此线程中的Callable提交给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需要通过命令行参数执行程序,因此我不想通过连接线程来执行此操作。
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. 我曾考虑过以单例方式执行此操作,并编写了一个Submit方法将我的Callable提交给ExecutorService实例,但是由于不熟悉api,所以我不确定这是否明智。
Any help is greatly appreciated, Thanks. 非常感谢任何帮助,谢谢。
I would try 我会尝试
static final ExecutorService service = Executors.newFixedThreadPool(4);
Callable call =
service.submit(call);
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);
}
}
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. 请注意,使用执行程序服务时,您无法控制任务实际启动的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.