2014-04-02 49 views
0

我正在一个项目中,我有多个接口和两个实现类需要实现这两个接口。如何使用多线程并行运行两个实现类?

假设我的第一个界面 -

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需要返回类型,但我的接口方法是无效的,所以不知道如何才能并行运行这两个。

+0

是的,这是可能的,但为什么要?比顺序运行它要复杂得多。 – chrylis

+0

我明白了..在我的情况下,abc和xyz两种方法都写入不同的数据库。所以我需要并行而不是顺序编写。 – AKIWEB

+0

重复[如何使用多线程并行运行两个类?](http://stackoverflow.com/questions/22755151/how-to-run-two-classes-in-parallel-using-multithreading/22755430#22755430)你已经问过。你最后一个问题没有答案吗? – Braj

回答

0
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() { 

     } 
    }); 
} 
+0

谢谢,这有助于很多。在我的例子中,我有大约7-8个实现,而不是当前的例子,我只有2个。在这种情况下,我是否需要继续为此创建新的'thread'?如果我比'8-9'多,它看起来不是很长的代码吗?或者还有其他的方式吗? – AKIWEB

+0

我更新了我的答案 – zella

+0

谢谢。在内部运行的方法中,我将TestA和TestB的调用权对吧?如果我有两个以上的人,我可以为他们做同样的事情吗?> – AKIWEB

相关问题