如何将 Callable 与 void 返回类型一起使用? [英] How to use Callable with void return type?
问题描述
我正在开发一个项目,其中有多个接口和两个需要实现这两个接口的实现类.
I am working on a project in which I have multiple interface and two Implementations classes which needs to implement these two interfaces.
假设我的第一个界面是 -
Suppose my first Interface is -
public Interface interfaceA {
public void abc() throws Exception;
}
它的实现是 -
public class TestA implements interfaceA {
// abc method
}
我是这样称呼它的 -
I am calling it like this -
TestA testA = new TestA();
testA.abc();
现在我的第二个界面是 -
Now my second interface is -
public Interface interfaceB {
public void xyz() throws Exception;
}
它的实现是 -
public class TestB implements interfaceB {
// xyz method
}
我是这样称呼它的 -
I am calling it like this -
TestB testB = new TestB();
testB.xyz();
问题陈述:-
现在我的问题是 - 有什么办法可以并行执行这两个实现类吗?我不想按顺序运行它.
Now my question is - Is there any way, I can execute these two implementation classes in parallel? I don't want to run it in sequential.
意思是,我想并行运行 TestA
和 TestB
实现?可以这样做吗?
Meaning, I want to run TestA
and TestB
implementation in parallel? Is this possible to do?
我想在这里使用 Callable 但不确定如何在这里使用带有 void 返回类型的 Callable -
I was thinking to use Callable here but not sure how to use Callable with void return type here -
我们以TestB类为例:
Let's use TestB class as an example:
public interface interfaceB {
public void xyz() throws Exception;
}
public class TestB implements interfaceB, Callable<?>{
@Override
public void xyz() throws Exception
{
//do something
}
@Override
public void call() throws Exception
{
xyz();
}
}
上面的代码给出了编译错误..
Above code gives compilation error..
更新:-
看起来很多人都建议使用 Runnable 而不是 callable.但不确定如何在这里使用 Runnable 以便我可以并行执行 TestA 和 TestB
.
It looks like lot of people are suggesting to use Runnable instead of callable. But not sure how do I use Runnable here so that I can execute TestA and TestB
in parallel.
推荐答案
您可以使用 java.lang.Thread 进行并行执行.但是,在大多数情况下,使用 java.util.concurrent.ExecutorService 更容易.后者提供了一个方法来提交一个Callable并返回一个Future以便稍后获取结果(或等待完成).
You can use java.lang.Thread for parallel execution. However, in most cases it's easier to use an java.util.concurrent.ExecutorService. The latter provides a method to submit a Callable and returns a Future to get the result later (or wait for completion).
如果 testA.abc() 和 testB.xyz() 应该并行执行,则使用 ExecutorService 来执行前者在一个单独的线程中,而后者在原始线程中执行.然后等待前者完成同步.
If testA.abc() and testB.xyz() should be executed in parallel, you use the ExecutorService to execute the former in a separate thread whereas the latter is executed in the original thread. Then you wait for the completion of the former for synchronization.
ExecutorService executor = ... // e.g. Executors.newFixedThreadPool(4);
Future<Void> future = executor.submit(new Callable<Void>() {
public Void call() throws Exception {
testA.abc();
return null;
}
});
testB.xyz();
future.get(); // wait for completion of testA.abc()
这篇关于如何将 Callable 与 void 返回类型一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!