Question

I'm calling two different main class which are within a for in my code, However I would like to run both of them at the same time.

for (int m=0; m<ListUser.size();m++){
System.out.println(ListUser.get(m));
 File user = new File(ManagedPlatformPath.properties()+"/"+ListPlatform.get(n)+" /"+ListUser.get(m)+".adf");
  if(user.exists()){
   System.out.println("Reading Information "+ListUser.get(m)+"");
    BACControlS.main(args);
    BACControlT.main(args);
  }
  else{
    System.out.println("Not Information "+ListUser.get(m)+"");
  }

How would be possible to run both BACControlS.main(args) and BACControlT.main(args) at the same time, instead to wait until one is finish.

Was it helpful?

Solution 3

Use an java.util.concurrent.ExecutorService. Creating java.lang.Threads in a loop, as other anwsers suggest, is a bad idea because threads are not limitless resources but your list of user names could be large.

Here's how the code would look with a java.util.concurrent.ExecutorService:

ExecutorService executorService = Executors.newFixedThreadPool(10);

try
{
  for (String userName : users)
  {
    File userFile = ...

    if (userFile.exists())
    {
      System.out.println("Reading Information " + userName);

      executorService.execute(
        new Runnable()
        {
          public void run()
          {        
            BACControlS.main(args);
          }
        }
      );

      executorService.execute(
        new Runnable()
        {
          public void run()
          {        
            BACControlT.main(args);
          }
        }
      );
    }
    else
    {
      System.out.println("Not Information " + userName);
    }
  }
}
finally
{
  executorService.shutdown();
}

OTHER TIPS

Spawn two threads.

new Thread(new Runnable() {
    public void run() {
        BACControlS.main(args);
    }
}).start();

new Thread(new Runnable() {
    public void run() {
        BACControlT.main(args);
    }
}).start();

In order to pass args down to those Runnable you may need to declare args as final

You should use threads for that. You can run it as:

Thread t1 = new Thread(new Runnable() {

@Override
public void run() {
  BACControlS.main(args);       
            }
});
t1.start();
Thread t2 = new Thread(new Runnable() {

@Override
public void run() {
  BACControlT.main(args);       
        }
});
t2.start();

Instead of

BACControlS.main(args);
BACControlT.main(args);

There are no means available to run 2 classes as both main classes are suppose to be different processes. So what you can do is use threads. Threads can run parallel. If both treads are in one process, CPU takes it as a single process and treat it as a single process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top