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? Is this possible to do?

Answers


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.

    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. Let's use TestB class as an example:

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.


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 -

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

Need Your Help