我正在开发一个项目,在该项目中我有多个接口(interface)和两个需要实现这两个接口(interface)的实现类。

假设我的第一个界面是 -

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

它的实现是——
public class TestA implements interfaceA {

    // abc method
}

我是这样称呼它的——
TestA testA = new TestA();
testA.abc();

现在我的第二个界面是 -
public Interface interfaceB {
    public String xyz() throws Exception;
}

它的实现是——
public class TestB implements interfaceB {

    // xyz method
}

我是这样称呼它的——
TestB testB = new TestB();
testB.xyz();

问题陈述:-

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

意思是,我想并行运行 TestATestB 实现?这是可能的吗?

最佳答案

当然有可能。你实际上有很多选择。首选一种是使用可调用和执行程序。

    final ExecutorService executorService = Executors.newFixedThreadPool(2);
    final ArrayList<Callable<String>> tasks = Lists.newArrayList(
            new Callable<String>()
            {
                @Override
                public String call() throws Exception
                {
                    return testA.abc();
                }
            },
            new Callable<String>()
            {
                @Override
                public String call() throws Exception
                {
                    return testB.xyz();
                }
            }
    );

    executorService.invokeAll(tasks);

此方法使您有机会从执行任务中获得结果。 InvokeAll 返回 Future 对象的列表。
    final List<Future<String>> futures = executorService.invokeAll(tasks);
    for (Future<String> future : futures)
    {
        final String resultOfTask = future.get();
        System.out.println(resultOfTask);
    }

如果您让您的类实现 Callable,您可以使您的代码更易于使用,然后您将减少准备任务列表所需的代码量。我们以 TestB 类为例:
public interface interfaceB {
    String xyz() throws Exception;
}

public class TestB implements interfaceB, Callable<String>{

    @Override
    public String xyz() throws Exception
    {
        //do something
        return "xyz";
    }

    @Override
    public String call() throws Exception
    {
        return xyz();
    }
}

那么你只需要
Lists.newArrayList(new TestB(), new TestA());

代替
final ArrayList<Callable<String>> tasks = Lists.newArrayList(
            new Callable<String>()
            {
                @Override
                public String call() throws Exception
                {
                    return testA.abc();
                }
            },
            new Callable<String>()
            {
                @Override
                public String call() throws Exception
                {
                    return testB.xyz();
                }
            }
    );

更重要的是,执行程序使您能够维护和重用 Thread 对象,这从性能和可维护性的角度来看是很好的。

关于java - 如何使用多线程并行运行两个类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22755151/

10-10 01:03
查看更多