问题描述
我可以使用Callable线程而不使用ExecutorService吗?我们可以使用Thread的Runnable和子类的实例,而不使用ExecutorService,这段代码正常工作。但是这段代码是一致的:
Can I use Callable threads without ExecutorService? We can use instances of Runnable and subclasses of Thread without ExecutorService and this code works normally. But this code works consistently:
public class Application2 {
public static class WordLengthCallable implements Callable {
public static int count = 0;
private final int numberOfThread = count++;
public Integer call() throws InterruptedException {
int sum = 0;
for (int i = 0; i < 100000; i++) {
sum += i;
}
System.out.println(numberOfThread);
return numberOfThread;
}
}
public static void main(String[] args) throws InterruptedException {
WordLengthCallable wordLengthCallable1 = new WordLengthCallable();
WordLengthCallable wordLengthCallable2 = new WordLengthCallable();
WordLengthCallable wordLengthCallable3 = new WordLengthCallable();
WordLengthCallable wordLengthCallable4 = new WordLengthCallable();
wordLengthCallable1.call();
wordLengthCallable2.call();
wordLengthCallable3.call();
wordLengthCallable4.call();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(0);
}
}
使用ExecutorService代码可以处理几个线程。
接口
通常是创建的,但是我的错误是在哪里?
With ExecutorService the code works with few threads. Where are my mistakes?
推荐答案
您可以提交 Runnable
它到 ExecutorService
,或者将它传递给 Thread
的构造函数,或者您可以调用其 run()
方法直接像调用任何接口
方法,而不涉及多线程。还有更多的用例,例如。 AWT EventQueue.invokeLater(Runnable)
,因此不要期望列表完成。
Given a Runnable
you can submit it to an ExecutorService
, or pass it to the constructor of Thread
or you can invoke its run()
method directly like you can invoke any interface
method without multi-threading involved. And there are more use cases, e.g. AWT EventQueue.invokeLater(Runnable)
so never expect the list to be complete.
c> Callable ,你有相同的选项,所以重要的是要强调,不像你的问题所暗示的,直接调用 call()
任何多线程。
Given a Callable
, you have the same options, so it’s important to emphasize that, unlike your question suggests, invoking call()
directly does not involve any multi-threading. It just executes the method like any other ordinary method invocation.
由于没有构造函数 Thread(Callable)
使用不带 ExecutorService
的可调用
代码:
Since there is no constructor Thread(Callable)
using a Callable
with a Thread
without an ExecutorService
requires slightly more code:
FutureTask<ResultType> futureTask = new FutureTask<>(callable);
Thread t=new Thread(futureTask);
t.start();
// …
ResultType result = futureTask.get(); // will wait for the async completion
这篇关于我可以使用Callable线程没有ExecutorService吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!