8

5 つの異なる内部メソッドを含む 1 つの Java メソッドがあります。パフォーマンスを向上させるために、これらのメソッドを並列に呼び出したいと考えています。

たとえば、メソッド 1、メソッド 2、... メソッド 5 をスレッドを使用して並列に実行します。

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

ただし、これら 5 つのメソッドはすべて、ビジネス ロジックが異なります。

4

6 に答える 6

18

次のようにします。

  1. メソッドごとに、そのメソッドをラップする Callable オブジェクトを作成します。
  2. Executor を作成します (固定スレッド プールの Executor で問題ありません)。
  3. すべての Callable をリストに入れて、Executor で呼び出します。

簡単な例を次に示します。

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 Executors の優れた入門書を提供しています。また、Java で何らかの種類のスレッド化を行っている場合、この本は素晴らしいものです。

于 2013-08-10T15:45:16.080 に答える
5

method1 を並行して実行するには、次のようにします。

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

すべてのメソッドに対してこれを行います。

method1 が終了するのを待つには、次のようにします。

t1.join();

他のすべてのスレッドについても同様です。

多くの人は、スレッドプールを使用しスレッドを拡張しないと言うでしょう。この方法を習得してから、そのアドバイスに従ってください。

于 2013-08-11T18:08:57.140 に答える
0

メソッドを並行して実行するには、5 つの異なるスレッドを使用する必要があります。コードは難しくありませんが、かなり退屈です。

並列コードをより簡単に楽しく書くことができる Gpars Tasks を参照してください。

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

于 2013-08-10T15:54:53.407 に答える