Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用多线程并行运行两个类?_Java_Multithreading_Parallel Processing_Executorservice_Callable - Fatal编程技术网

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

Java 如何使用多线程并行运行两个类?,java,multithreading,parallel-processing,executorservice,callable,Java,Multithreading,Parallel Processing,Executorservice,Callable,我正在从事一个项目,其中我有多个接口和两个实现类,需要实现这两个接口 假设我的第一个接口是- public Interface interfaceA { public String abc() throws Exception; } 而其实施是— public class TestA implements interfaceA { // abc method } 我这样称呼它- TestA testA = new TestA(); testA.abc(); TestB t

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

假设我的第一个接口是-

public Interface interfaceA {
    public String abc() throws Exception;
}
而其实施是—

public class TestA implements interfaceA {

    // abc method
}
我这样称呼它-

TestA testA = new TestA();
testA.abc();
TestB testB = new TestB();
testB.xyz();
现在我的第二个界面是-

public Interface interfaceB {
    public String xyz() throws Exception;
}
而且它的实施是非常困难的-

public class TestB implements interfaceB {

    // xyz method   
}
我这样称呼它-

TestA testA = new TestA();
testA.abc();
TestB testB = new TestB();
testB.xyz();
问题陈述:-

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


也就是说,我想并行运行
TestA
TestB
实现?这可能吗?

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

ThreadA{

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

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

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

当然有可能。实际上你有很多选择。首选方法是使用callable和Executor

    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);
而不是

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();
                }
            }
    );
final ArrayList tasks=Lists.newArrayList(
新的可调用()
{
@凌驾
公共字符串调用()引发异常
{
返回testA.abc();
}
},
新的可调用()
{
@凌驾
公共字符串调用()引发异常
{
返回testB.xyz();
}
}
);

此外,executors使您能够维护和重用线程对象,这从性能和可维护性的角度来看都很好。

您可以这样尝试:

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;
    }
}
publicstaticvoidmain(String[]args)抛出InterruptedException{
Executors.newCachedThreadPool().invokeAll(Arrays.asList(
新的可调用(){
@重写公共字符串调用(){return newtesta().abc();}
},
新的可调用(){
@重写公共字符串调用(){return new TestB().xyz();}
}));
}
公共接口{
公共字符串abc()引发异常;
}
公共接口B{
公共字符串xyz()引发异常;
}
类TestA实现了InterfaceA{
@重写公共字符串abc(){
System.out.println(“内部A”);返回null;
}
}
类TestB实现了InterfaceB{
@重写公共字符串xyz(){
System.out.println(“内部B”);返回null;
}
}
试试这个

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

使用回调机制返回结果

import java.util.ArrayList;
导入java.util.List;
公开课演示123{
公共静态void main(字符串[]args){
列表a=新的ArrayList();
列表b=新的ArrayList();
TestA TestA=新约书();
TestB TestB=新的TestB();
a、 添加(种皮);
b、 添加(testB);
用于(最终接口a i:a){
新线程(newrunnable()){
@凌驾
公开募捐{
试一试{
i、 回调(i.abc());
}捕获(例外e){
e、 printStackTrace();
}
}
}).start();
}
用于(最终接口b i:b){
新线程(newrunnable()){
@凌驾
公开募捐{
试一试{
i、 回调(i.xyz());
}捕获(例外e){
e、 printStackTrace();
}
}
}).start();
}
}
}
接口MyCallback{
公共无效回调(字符串值);
}
接口A扩展了MyCallback{
公共字符串abc()引发异常;
}
类TestA实现了InterfaceA{
@凌驾
公共字符串abc()引发异常{
返回“abc”;
}
@凌驾
公共无效回调(字符串值){
System.out.println(“返回值:“+value”);
}
}
接口B扩展了MyCallback{
公共字符串xyz()引发异常;
}
类TestB实现了InterfaceB{
@凌驾
公共字符串xyz()引发异常{
返回“xyz”;
}
@凌驾
公共无效回调(字符串值){
System.out.println(“返回值:“+value”);
}
}

假设我有30个这样的实现类,那么我需要做30次。我想不是吧?我仍然可以重复使用我猜的线程?如何接收方法
abc
xyz
的返回值?@Braj在这种情况下,使用
ExcuterService
运行线程
submit
method返回一个
Future
对象,您可以通过该对象获取返回值。@akiiddweeber创建一个通用线程实现,并作为一个想法-使用refection调用您的方法。谢谢。假设我有30个这样的实现类,那么我需要在一个单独的调用方法中执行30次。我想不是吧?我想我仍然可以重用一些线程?ExecutorService当然会重用线程(取决于您选择的策略)。非常感谢。你能提供一个例子吗?如果可能的话,在我的代码场景的基础上,让你的类实现可调用,那么你的代码就更容易使用了?这会很有帮助的。非常感谢。所以如果我调用这个
Lists.newArrayList(newtestb(),newtesta())
然后它将分别并行地自动调用每个
调用
方法?我想我还是需要使用ExecutorsService来完成这项任务。。是吗?呵呵,是的,您仍然需要使用ExecutorService,它只会减少创建任务所需的代码量。ExecutorService使您能够更灵活地维护任务的执行,例如提供超时,或者使用不同的线程管理策略,例如CachedThreadPool。使用此解决方案,从代码中检索结果将非常困难。
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();
                }
            }
    );
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;
    }
}
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);
    }
}