简体   繁体   中英

Launch multiple main methods at the same time in JAVA without a bash script

I want to launch multiple main methods as clients for my program. and I should give each one separately its own arguments. Is there a way to do this without using a bash script ? And if not, is it a solution to actually develop another method and pass arguments as variables if possible ?

Try using Threads. You can create multiple threads and start them all at the same time.

http://docs.oracle.com/javase/tutorial/essential/concurrency/

EDIT: maybe this helps too. How to run two methods simultaneously

You can have a main dispatcher , that creates Threads that will invoke each client main method.

public class Dispatcher {
   public static void main(String args[]) throws InterruptedException {
      final Thread thread1 = new Thread(() -> Client1.main(args1));
      final Thread thread2 = new Thread(() -> Client2.main(args2));
      final Thread thread3 = new Thread(() -> Client3.main(args3));

      thread1.start();
      thread2.start();
      thread3.start();

      thread1.join();
      thread2.join();
      thread3.join();
   }
}

You have to figure out how to pass the arguments ( args1 , args2 , args3 ), this is not detailed in the question.

Thread. join() is used to wait for the Threads to finish, if you want to do some later actions (prompt something for example). If you don't call it, it will still work because they are not daemon threads , but you won't be able to do actions after they are finished.

However, with more context, we may provide you a better solution and avoid the XY problem .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM