java线程的两个类,如何使用多线程并行运行两个类?

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 String abc() throws Exception;

}

And its implementation is -

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 String xyz() throws Exception;

}

And its implementation is -

public class TestB implements interfaceB {

// xyz method

}

I am calling it like this -

TestB testB = new TestB();

testB.xyz();

Problem Statement:-

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.

Meaning, I want to run TestA and TestB implementation in parallel? Is this possible to do?

解决方案

Sure it is possible. You have actually many options. Preferred one is using callable and executors.

final ExecutorService executorService = Executors.newFixedThreadPool(2);

final ArrayList> tasks = Lists.newArrayList(

new Callable()

{

@Override

public String call() throws Exception

{

return testA.abc();

}

},

new Callable()

{

@Override

public String call() throws Exception

{

return testB.xyz();

}

}

);

executorService.invokeAll(tasks);

This method gives you opportunity to get a result from executions of your tasks. InvokeAll returns a list of Future objects.

final List> futures = executorService.invokeAll(tasks);

for (Future future : futures)

{

final String resultOfTask = future.get();

System.out.println(resultOfTask);

}

You can make your code easier to use if you make your classes implements Callable, then you will reduce amount of code needed to prepare list of tasks. Let's use TestB class as an example:

public interface interfaceB {

String xyz() throws Exception;

}

public class TestB implements interfaceB, Callable{

@Override

public String xyz() throws Exception

{

//do something

return "xyz";

}

@Override

public String call() throws Exception

{

return xyz();

}

}

Then you will need just

Lists.newArrayList(new TestB(), new TestA());

instead of

final ArrayList> tasks = Lists.newArrayList(

new Callable()

{

@Override

public String call() throws Exception

{

return testA.abc();

}

},

new Callable()

{

@Override

public String call() throws Exception

{

return testB.xyz();

}

}

);

Whats more, executors gives you power to maintain and reuse Thread objects which is good from performance and maintainability perspective.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值