How to run different methods parallely

2019-06-20 09:38发布

I have one java method which contains 5 different internal methods. For performance improvement, I want to call these methods parallely.

e.g. run method1, method2, ... method5 parallel using thread.

private void getInformation() throws SQLException,
            ClassNotFoundException, NamingException {
    method1();
    method2();
    method3();
    method4();
    method5();
}

but all these 5 methods have different business logic.

5条回答
何必那么认真
2楼-- · 2019-06-20 10:16

Do something like this:

  1. For each method, create a Callable object that wraps that method.
  2. Create an Executor (a fixed thread pool executor should be fine).
  3. Put all your Callables in a list and invoke them with the Executor.

Here's a simple example:

public void testThread()
{

   //create a callable for each method
   Callable<Void> callable1 = new Callable<Void>()
   {
      @Override
      public Void call() throws Exception
      {
         method1();
         return null;
      }
   };

   Callable<Void> callable2 = new Callable<Void>()
   {
      @Override
      public Void call() throws Exception
      {
         method2();
         return null;
      }
   };

   Callable<Void> callable3 = new Callable<Void>()
   {
      @Override
      public Void call() throws Exception
      {
         method3();
         return null;
      }
   };

   //add to a list
   List<Callable<Void>> taskList = new ArrayList<Callable<Void>>();
   taskList.add(callable1);
   taskList.add(callable2);
   taskList.add(callable3);

   //create a pool executor with 3 threads
   ExecutorService executor = Executors.newFixedThreadPool(3);

   try
   {
      //start the threads and wait for them to finish
      executor.invokeAll(taskList);
   }
   catch (InterruptedException ie)
   {
      //do something if you care about interruption;
   }

}

private void method1()
{
   System.out.println("method1");
}

private void method2()
{
   System.out.println("method2");
}

private void method3()
{
   System.out.println("method3");
}

Make sure each method does not share state (like a common mutable field in the same class) or you may get unexpected results. Oracle provides a good introduction to Java Executors. Also, this book is awesome if you are doing any kind of threading in java.

查看更多
地球回转人心会变
3楼-- · 2019-06-20 10:19

You have to use 5 different threads to execute your methods in parallel, the code it's not difficult but pretty boring.

You may want to have a look to Gpars Tasks, which make writing parallel code much more easy and enjoyable.

http://gpars.org/1.0.0/guide/guide/dataflow.html#dataflow_tasks

查看更多
Juvenile、少年°
4楼-- · 2019-06-20 10:22

You can use high level concurrency instrument in Java - thread pool. But anyway you will have to create Runnable objects (tasks) and then use thread pool's method - invokeAll(). Please take a look at Oracle concurrency tutorial

查看更多
一纸荒年 Trace。
5楼-- · 2019-06-20 10:26

take a look at java.util.concurrent http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html and the tutorial: http://docs.oracle.com/javase/tutorial/essential/concurrency/ basically, you will have to create an executorserice, some class extending Runnable, and invoke them

查看更多
成全新的幸福
6楼-- · 2019-06-20 10:29

To run method1 in parallel, do following:

Thread t1=new Thread() {
   public void run() {
       method1();
   }
};
t1.start();

Do this for all your methods.

To wait method1 to finish, do

t1.join();

and so for all other threads.

Many people will tell you use threadpool and do not extend Thread - all this has little sense for you just now. Master this way and only then follow that advices.

查看更多
登录 后发表回答