如何为for循环中执行的一系列操作实现forkjoin

时间:2011-10-27 12:54:30

标签: java java-7 fork-join

我有一个发件人列表,我必须单独发送邮件。目前我正在迭代列表构建正文(因为它对不同的人不同),然后发送它们。我怎样才能使用forkjoin。我尝试使用recusiveAction,但我猜它只适用于递归任务。

互联网上提供的所有示例都是使用RecursiveAction实现的。还有其他类我可以实现这个。

2 个答案:

答案 0 :(得分: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));
    }
  }
}

答案 1 :(得分: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());
        }
    }    
}

使用此代码,您将能够获得响应以及引发的任何异常。