2011-10-27 3 views
2

私はそれらのための送信者のリストを持っています。私は並行してメールを個別に送信する必要があります。現在、リストを反復しています異なる人々のために異なっている)、それからそれらを送る。これにはどのようにしてforkjoinを使用できますか?私はrecusiveActionを使ってみましたが、私は再帰的な作業のためにしか思いません。今for forループで行われている一連のアクションのためのforkjoinの実装方法

インターネットで利用できるすべての例は、RecursiveActionで実装されています。私がこれを実装できる他のクラスはありますか?

答えて

1

ServiceExecutorsはこのためにうまく機能します。彼らにはJavaが付属しています。私は良い答えだ閲覧

import java.util.*; 
import java.util.concurrent.*; 

public class SendMailExample 
{ 
    public static void main(String[] args) throws Exception 
    { 
    ExecutorService executor = Executors.newFixedThreadPool(3); 

    Collection<Future> futures = new ArrayList<Future>(); 
    futures.add(executor.submit(new Mailer("thread1"))); 
    futures.add(executor.submit(new Mailer("thread2"))); 
    futures.add(executor.submit(new Mailer("thread3"))); 

    for (Future future : futures) 
    { 
     future.get(); 
    } 
    executor.shutdown(); 
    } 

    static class Mailer implements Runnable 
    { 
    private Object message; 

    public Mailer(Object message) 
    { 
     this.message = message; 
    } 

    public void run() 
    { 
     System.out.println("Sending message " + String.valueOf(message)); 
    } 
    } 
} 
0

:このコードで

package Test1; 

import java.util.*; 
import java.util.concurrent.*; 
import static java.util.Arrays.asList; 

public class Sums 
{ 
    static class Sum implements Callable<Long> 
    { 
     private final long from; 
     private final long to; 
     Sum(long from, long to) 
     { 
      this.from = from; 
      this.to = to; 
     } 

     @Override 
     public Long call() 
     { 
      long acc = 0; 
      if(from == 0) 
      { 
       try 
       { 
        Thread.sleep(5000); 
       } 
       catch (InterruptedException e) 
       { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
      System.out.println(from); 
      for (long i = from; i <= to; i++) 
      { 
       acc = acc + i; 
      } 
      return acc; 
     }     
    } 

    public static void main(String[] args) throws Exception 
    { 
     ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); 
     List <Future<Long>> results = executor.invokeAll(asList(
     new Sum(0, 10), new Sum(100, 1000), new Sum(10000, 1000000) 
     )); 
     executor.shutdown(); 

     for (Future<Long> result : results) 
     { 
      System.out.println(result.get()); 
     } 
    }  
} 

を、あなたは応答してもスローされた例外を取得することができます。

関連する問題