Search code examples
javadesign-patternsfactory-patternjava-threads

How to crate a list of objects and execute them one by one?


I need to create a list of objects and execute them one by one in 2-3 threads. When the first object finishes executing, another one starts to execute in it's place. All objects are members of the same class with different input parameters. There can be a lot of objects of this class and therefor I cannot hardcode them as written below. I like to find the best way to solving this issue.

// The simple class. He do nothing 
public class SomeClsass implements Runnable{

    run(){
        sum();
    }
    
    // The simple function
    private void sum(){
        
        // Some code. It doesn't meaning 
        int j =0;
        for(int i=0; i<=10000; i++){
            j=i; 
            
        }
    }
}

public static void main(String args[]){
    
    // I don't wont to create objects as here
    SomeClass someClass = new SomeClass();
    SomeClass someClass1 = new SomeClass();
    SomeClass someClass2 = new SomeClass();
    SomeClass someClass3 = new SomeClass();
    // ...... more then 1000 objects
    
    
    // When this two objects finishes one by one next object will starts executing 
    someClass.run();
    someClass1.run();
    

}

Solution

  • I would recommend using Executors.newFixedThreadPool too, but with a try catch statement wrapping it.

    ExecutorService service = null;
    try {
      service = Executors.newFixedThreadPool(3);
    
      SomeClass someClass = new SomeClass();
    
      for (int i = 0; i < 10; i++) {
        service.submit(someClass); // Here you could also use a lambda instead of implementing the Runnable interface (() -> someClass.sum())
      }
    finally {
      if (service != null) service.shutdown();
    }
    

    The example above shows how to use multiple threads to execute your piece of code concurrently, but it is not thread-safe. If you want to have multiple threads executing one by one your sum() method, you could use synchronize in your sum() method signature or inside the try catch block (synchronize(someClass) { for... })

    There are other features in the Java Concurrency API that can be used for this case. I recommend that you look them up before choosing one, because there are other options that are thread-safe, for example atomic classes, synchronized blocks, the Lock framework and cyclic barriers. But the example above is completely usable.