Java 如何并行运行不同的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18162863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:56:41  来源:igfitidea点击:

How to run different methods parallely

javamultithreadingparallel-processing

提问by user1037452

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

我有一个包含 5 个不同内部方法的 java 方法。为了提高性能,我想并行调用这些方法。

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

例如,使用线程并行运行method1、method2、...method5。

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

but all these 5 methods have different business logic.

但是这 5 种方法都有不同的业务逻辑。

采纳答案by lreeder

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.
  1. 对于每个方法,创建一个包装该方法的 Callable 对象。
  2. 创建一个 Executor(一个固定的线程池执行器应该没问题)。
  3. 将所有 Callable 放在一个列表中,并使用 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 bookis awesome if you are doing any kind of threading in java.

确保每个方法不共享状态(如同一类中的公共可变字段),否则您可能会得到意想不到的结果。Oracle很好地介绍了 Java Executors。此外,如果您在 Java 中进行任何类型的线程处理,这本书也很棒。

回答by XZen

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

您可以在 Java 中使用高级并发工具 - 线程池。但无论如何,您必须创建 Runnable 对象(任务),然后使用线程池的方法 - invokeAll()。请看Oracle并发教程

回答by jlb

take a look at java.util.concurrent http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.htmland 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

看看 java.util.concurrent http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html和教程:http: //docs.oracle。 com/javase/tutorial/essential/concurrency/基本上,你必须创建一个 executorserice,一些扩展 Runnable 的类,并调用它们

回答by pditommaso

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

你必须使用 5 个不同的线程来并行执行你的方法,代码不难但很无聊。

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

您可能想看看 Gpars Tasks,它使编写并行代码变得更加容易和愉快。

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

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

回答by Alexei Kaigorodov

To run method1 in parallel, do following:

要并行运行 method1,请执行以下操作:

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

Do this for all your methods.

为您的所有方法执行此操作。

To wait method1 to finish, do

要等待方法 1 完成,请执行

t1.join();

and so for all other threads.

对于所有其他线程也是如此。

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

很多人会告诉你使用线程不要扩展线程——所有这些对你来说都没有意义。掌握这种方式,然后才能遵循该建议。