繁体   English   中英

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

[英]How to run two implementation classes in parallel using multithreading?

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

假设我的第一个接口是-

public Interface interfaceA {
    public void abc() throws Exception;
}

它的实现是-

public class TestA implements interfaceA {

    // abc method
}

我这样称呼它-

TestA testA = new TestA();
testA.abc();

现在我的第二个界面是-

public Interface interfaceB {
    public void xyz() throws Exception;
}

它的实现是-

public class TestB implements interfaceB {

    // xyz method   
}

我这样称呼它-

TestB testB = new TestB();
testB.xyz();

问题陈述:-

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

意思是,我要并行运行TestATestB实现吗? 这可能吗? 最初,我想到使用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() {

        }
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM