如何并行运行不同的方法 [英] How to run different methods parallely

查看:94
本文介绍了如何并行运行不同的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

but all these 5 methods have different business logic.

推荐答案

执行以下操作:

  1. 对于每个方法,创建一个包装该方法的Callable对象.
  2. 创建一个执行程序(固定线程池执行程序应该没问题).
  3. 将所有可调用对象放入列表中,然后使用执行程序调用它们.

这是一个简单的例子:

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");
}

确保每个方法都不共享状态(如同一类中的公共可变字段),否则您可能会得到意想不到的结果. Oracle提供了关于Java执行器的很好的介绍.另外,如果您正在做任何事情,这本书很棒Java中的线程.

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.

这篇关于如何并行运行不同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆