简体   繁体   English

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

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

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? 意思是,我想并行运行TestATestB实现? 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<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);

This method gives you opportunity to get a result from executions of your tasks. 此方法使您有机会从执行任务中获得结果。 InvokeAll returns a list of Future objects. InvokeAll返回Future对象列表。

    final List<Future<String>> futures = executorService.invokeAll(tasks);
    for (Future<String> 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. 如果使类实现Callable,则可以使代码更易于使用,然后减少准备任务列表所需的代码量。 Let's use TestB class as an example: 我们以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();
    }
}

Then you will need just 那你就需要了

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

instead of 代替

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();
                }
            }
    );

Whats more, executors gives you power to maintain and reuse Thread objects which is good from performance and maintainability perspective. 更重要的是,执行程序赋予您维护和重用Thread对象的能力,从性能和可维护性的角度来看,这是很好的。

Create Two Thread and run two implementation parallely. 创建两个线程并并行运行两个实现。 Code snippet - 代码段 -

ThreadA{

  public void run(){
      TestA testA = new TestA();
      testA.abc();
  }
}

... ...

ThreadB{

  public void run(){
      TestB testB = new TestB();
      testB.xyz();
  }
}

Start this two thread from main method - 从main方法开始这两个线程 -

public static void main(String[] args){
    new ThreadA().start();
    new ThreadB().start();
}

Try this one 试试这个吧

Collect all the classes of same interface and call them in Multi threading. 收集相同接口的所有类,并在多线程中调用它们。

Use Callback mechanism to get the result back 使用回调机制来获取结果

import java.util.ArrayList;
import java.util.List;

public class Demo123 {
    public static void main(String[] args) {

        List<InterfaceA> a = new ArrayList<InterfaceA>();
        List<InterfaceB> b = new ArrayList<InterfaceB>();

        TestA testA = new TestA();
        TestB testB = new TestB();

        a.add(testA);
        b.add(testB);

        for (final InterfaceA i : a) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        i.callback(i.abc());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        for (final InterfaceB i : b) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        i.callback(i.xyz());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

    }
}

interface MyCallback {
    public void callback(String value);
}

interface InterfaceA extends MyCallback {
    public String abc() throws Exception;
}

class TestA implements InterfaceA {

    @Override
    public String abc() throws Exception {
        return "abc";
    }

    @Override
    public void callback(String value) {
        System.out.println("value returned:" + value);
    }
}

interface InterfaceB extends MyCallback {
    public String xyz() throws Exception;
}

class TestB implements InterfaceB {

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

    @Override
    public void callback(String value) {
        System.out.println("value returned:" + value);
    }
}

You may try it like this: 你可以这样试试:

public static void main(String[] args) throws InterruptedException {
    Executors.newCachedThreadPool().invokeAll(Arrays.asList(
        new Callable<String>() {
            @Override public String call() { return new TestA().abc(); }
        },
        new Callable<String>() {
            @Override public String call() { return new TestB().xyz(); }
        }));
}

public interface InterfaceA {
    public String abc() throws Exception;
}

public interface InterfaceB {
    public String xyz() throws Exception;
}

class TestA implements InterfaceA {
    @Override public String abc() {
        System.out.println("Inside A"); return null;
    }
}

class TestB implements InterfaceB {

    @Override public String xyz() {
        System.out.println("Inside B"); return null;
    }
}

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

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