Java 如何使用多线程并行运行两个实现类?

Java 如何使用多线程并行运行两个实现类?,java,multithreading,runnable,executorservice,callable,Java,Multithreading,Runnable,Executorservice,Callable,我正在从事一个项目,其中我有多个接口和两个实现类,需要实现这两个接口 假设我的第一个接口是- public Interface interfaceA { public void abc() throws Exception; } 而其实施是— public class TestA implements interfaceA { // abc method } 我这样称呼它- TestA testA = new TestA(); testA.abc(); TestB tes

我正在从事一个项目,其中我有多个接口和两个实现类,需要实现这两个接口

假设我的第一个接口是-

public Interface interfaceA {
    public void abc() throws Exception;
}
而其实施是—

public class TestA implements interfaceA {

    // abc method
}
我这样称呼它-

TestA testA = new TestA();
testA.abc();
TestB testB = new TestB();
testB.xyz();
现在我的第二个界面是-

public Interface interfaceB {
    public void xyz() throws Exception;
}
而且它的实施是非常困难的-

public class TestB implements interfaceB {

    // xyz method   
}
我这样称呼它-

TestA testA = new TestA();
testA.abc();
TestB testB = new TestB();
testB.xyz();
问题陈述:-

现在我的问题是-有没有办法,我可以并行执行这两个实现类?我不想按顺序运行它

也就是说,我想并行运行
TestA
TestB
实现?这可能吗?最初我想使用Callable,但Callable需要返回类型,但我的接口方法无效,因此不确定如何并行运行这两个方法

Thread thread1 = new Thread(new Runnable() {
    public void run() {
        TestB testB = new TestB();
        testB.xyz();
    }
});
Thread thread2 = new Thread(new Runnable() {
    public void run() {
        TestA testA = new TestA();
        testA.abc();
    }
});

thread1.start();
thread2.start();
另一种方法-如果你有很多可运行的

ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
    service.submit(new Runnable() {
        public void run() {

        }
    });
}
ExecutorService=Executors.newFixedThreadPool(10);
对于(int i=0;i<10;i++){
提交(新的Runnable(){
公开募捐{
}
});
}

是的,这是可能的,但您为什么要这样做?这比按顺序运行要复杂得多。我明白了。。在我的例子中,abc和xyz两种方法都写入不同的数据库。所以我需要并行地写,而不是顺序地写。重复你已经问过的。在你的最后一个问题中,你没有得到任何答案吗?实际上它有点不同,在那个问题中-我有一个返回类型作为string,而在这里我没有返回类型作为string。我有空。。请阅读这个问题,然后你就会明白。谢谢,这很有帮助。在我的示例中,我有大约7-8个实现,而当前的示例中我只有2个。在这种情况下,我需要继续为此制作新的
线程吗?如果我的代码超过
8-9
,它看起来不是很长吗。或者还有其他方法吗?谢谢。在run方法内部,我会调用TestA和TestB,对吗?如果我有两个以上,我也可以为他们做同样的事情?>是的。在您的情况下,需要为每个实现创建runnable并提交每个runnable。