Search code examples
javamultithreadingfuturerunnablecallable

Have two different Implementations for an interface execute on different thread


I have a interface say VegetableCreation with a method:

public void writeVeggieDataIntoFile();

and two different class called Apple and Mango that implement VegetableCreation.

And there is a factory class VegetableFactory with a create() method:

public class VegetableFactory {
    public VegetableCreation create(String arg0) {

        if (arg0.equals("Apple"))
           return new Apple();
        else if (arg0.equals("Mango")
           return new Mango();
        else {
           // create and return both apple and mango by spawning two different threads
           // so that the writeVeggieDataIntoFile();  gets invoked concurrently
           // for both apple and mango and two different file is created
        }
    }
}

What I'm basically trying to achieve here is that when I call the VegetableFactory class's create() method from a client class's main() method and pass any string value other than "Apple" or "Mango" as a run time argument. I want two different threads to work on each Apple and Mango object and work concurrently on each writeVeggieDataIntoFile() method.

Any suggestion on design strategy / or which concurrent APIs to use etc. would be highly appreciated.

P.S.: I should be calling it fruit** and not vegetable*


Solution

  • Look into the Composite pattern, and then build a CompositeVegetable which when told to "do it's thing" launches two threads, one which does one thing, the other doing the other thing.

    public class BothVegetable implements Vegetable {
        public void writeVeggieDataInfoFile() {
            Thread thread1 = new Thread(new AppleRunnable());
            Thread thread2 = new Thread(new MangoRunnable());
            thread1.start();
            thread2.start();
            thread1.join();
            thread2.join();
        }
    }
    
    // and in your factory
    
        return new CompositeVegetable();
    

    PS. Your vegetables look like fruits to me!