繁体   English   中英

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

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

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

假设我的第一个接口是 -

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对象的能力,从性能和可维护性的角度来看,这是很好的。

创建两个线程并并行运行两个实现。 代码段 -

ThreadA{

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

...

ThreadB{

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

从main方法开始这两个线程 -

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

试试这个吧

收集相同接口的所有类,并在多线程中调用它们。

使用回调机制来获取结果

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

你可以这样试试:

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