ITeye博客

Java并发编程-Executor框架+实例

iaspecwang · 2013-08-24 08:14 · java线程 · 企业架构 · Markdown

Executor框架是指java 5中引入的一系列并发库中与executor相关的一些功能类,其中包括线程池,Executor,Executors,ExecutorService,CompletionService,Future,Callable等。运用该框架能够很好的将任务分成一个个的子任务,使并发编程变得方便。该框架的类图(方法并没有都表示出来)如下: 

创建线程池的介绍,摘自http://mshijie.iteye.com/blog/366591 
创建线程池 
Executors类,提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口。 
public static ExecutorService newFixedThreadPool(int nThreads) 
创建固定数目线程的线程池。 
public static ExecutorService newCachedThreadPool() 
创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。 
public static ExecutorService newSingleThreadExecutor() 
创建一个单线程化的Executor。 
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 
创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。 

本文主要是用该Executor框架来完成一个任务:求出10000个随机数据中的top 100. 

Note:本文只是用Executor来做一个例子,并不是用最好的办法去求10000个数中最大的100个数。 

具体的实现如下: 
1. 随机产生10000个数(范围1~9999),并存放在一个文件中。 
2. 读取该文件的数值,并存放在一个数组中。 
3. 采用Executor框架,进行并发操作,将10000个数据用10个线程来做,每个线程完成1000=(10000/10)个数据的top 100操作。 
4. 将10个线程返回的各个top 100数据,重新计算,得出最后的10000个数据的top 100. 

随机产生数和读取随机数文件的类如下: 

Java代码  收藏代码

  1. package my.concurrent.demo;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.File;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.io.FileWriter;
  8. import java.io.IOException;
  9. import java.util.Random;
  10. public class RandomUtil {
  11. private static final int RANDOM_SEED= 10000;
  12. private static final int SIZE = 10000;
  13. /**
  14. * 产生10000万个随机数(范围1~9999),并将这些数据添加到指定文件中去。
  15. *
  16. * 例如:
  17. *
  18. * 1=7016
  19. * 2=7414
  20. * 3=3117
  21. * 4=6711
  22. * 5=5569
  23. * ... ...
  24. * 9993=1503
  25. * 9994=9528
  26. * 9995=9498
  27. * 9996=9123
  28. * 9997=6632
  29. * 9998=8801
  30. * 9999=9705
  31. * 10000=2900
  32. */
  33. public static void generatedRandomNbrs(String filepath) {
  34. Random random = new Random();
  35. BufferedWriter bw = null;
  36. try {
  37. bw = new BufferedWriter(new FileWriter(new File(filepath)));
  38. for (int i = 0; i < SIZE; i++) {
  39. bw.write((i + 1) + "=" + random.nextInt(RANDOM_SEED));
  40. bw.newLine();
  41. }
  42. } catch (IOException e) {
  43. // TODO Auto-generated catch block
  44. e.printStackTrace();
  45. } finally {
  46. if (null != bw) {
  47. try {
  48. bw.close();
  49. } catch (IOException e) {
  50. // TODO Auto-generated catch block
  51. e.printStackTrace();
  52. } finally {
  53. bw = null;
  54. }
  55. }
  56. }
  57. }
  58. /**
  59. * 从指定文件中提取已经产生的随机数集
  60. */
  61. public static int[] populateValuesFromFile(String filepath) {
  62. BufferedReader br = null;
  63. int[] values = new int[SIZE];
  64. try {
  65. br = new BufferedReader(new FileReader(new File(filepath)));
  66. int count = 0;
  67. String line = null;
  68. while (null != (line = br.readLine())) {
  69. values[count++] = Integer.parseInt(line.substring(line
  70. .indexOf("=") + 1));
  71. }
  72. } catch (FileNotFoundException e) {
  73. // TODO Auto-generated catch block
  74. e.printStackTrace();
  75. } catch (NumberFormatException e) {
  76. // TODO Auto-generated catch block
  77. e.printStackTrace();
  78. } catch (IOException e) {
  79. // TODO Auto-generated catch block
  80. e.printStackTrace();
  81. } finally {
  82. if (null != br) {
  83. try {
  84. br.close();
  85. } catch (IOException e) {
  86. // TODO Auto-generated catch block
  87. e.printStackTrace();
  88. } finally {
  89. br = null;
  90. }
  91. }
  92. }
  93. return values;
  94. }
  95. }

编写一个Calculator 类, 实现Callable接口,计算指定数据集范围内的top 100. 

Java代码  收藏代码

  1. package my.concurrent.demo;
  2. import java.util.Arrays;
  3. import java.util.concurrent.Callable;
  4. public class Calculator implements Callable<Integer[]> {
  5. /** 待处理的数据 */
  6. private int[] values;
  7. /** 起始索引 */
  8. private int startIndex;
  9. /** 结束索引 */
  10. private int endIndex;
  11. /**
  12. * @param values
  13. * @param startIndex
  14. * @param endIndex
  15. */
  16. public Calculator(int[] values, int startIndex, int endIndex) {
  17. this.values = values;
  18. this.startIndex = startIndex;
  19. this.endIndex = endIndex;
  20. }
  21. public Integer[] call() throws Exception {
  22. // 将指定范围的数据复制到指定的数组中去
  23. int[] subValues = new int[endIndex - startIndex + 1];
  24. System.arraycopy(values, startIndex, subValues, 0, endIndex
  25. - startIndex + 1);
  26. Arrays.sort(subValues);
  27. // 将排序后的是数组数据,取出top 100 并返回。
  28. Integer[] top100 = new Integer[100];
  29. for (int i = 0; i < 100; i++) {
  30. top100[i] = subValues[subValues.length - i - 1];
  31. }
  32. return top100;
  33. }
  34. /**
  35. * @return the values
  36. */
  37. public int[] getValues() {
  38. return values;
  39. }
  40. /**
  41. * @param values
  42. *            the values to set
  43. */
  44. public void setValues(int[] values) {
  45. this.values = values;
  46. }
  47. /**
  48. * @return the startIndex
  49. */
  50. public int getStartIndex() {
  51. return startIndex;
  52. }
  53. /**
  54. * @param startIndex
  55. *            the startIndex to set
  56. */
  57. public void setStartIndex(int startIndex) {
  58. this.startIndex = startIndex;
  59. }
  60. /**
  61. * @return the endIndex
  62. */
  63. public int getEndIndex() {
  64. return endIndex;
  65. }
  66. /**
  67. * @param endIndex
  68. *            the endIndex to set
  69. */
  70. public void setEndIndex(int endIndex) {
  71. this.endIndex = endIndex;
  72. }
  73. }

使用CompletionService实现 

Java代码  收藏代码

  1. package my.concurrent.demo;
  2. import java.util.Arrays;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.ExecutorCompletionService;
  5. import java.util.concurrent.ExecutorService;
  6. import java.util.concurrent.Executors;
  7. public class ConcurrentCalculator {
  8. private ExecutorService exec;
  9. private ExecutorCompletionService<Integer[]> completionService;
  10. private int availableProcessors = 0;
  11. public ConcurrentCalculator() {
  12. /*
  13. * 获取可用的处理器数量,并根据这个数量指定线程池的大小。
  14. */
  15. availableProcessors = populateAvailableProcessors();
  16. exec = Executors.newFixedThreadPool(availableProcessors);
  17. completionService = new ExecutorCompletionService<Integer[]>(exec);
  18. }
  19. /**
  20. * 获取10000个随机数中top 100的数。
  21. */
  22. public Integer[] top100(int[] values) {
  23. /*
  24. * 用十个线程,每个线程处理1000个。
  25. */
  26. for (int i = 0; i < 10; i++) {
  27. completionService.submit(new Calculator(values, i * 1000,
  28. i * 1000 + 1000 - 1));
  29. }
  30. shutdown();
  31. return populateTop100();
  32. }
  33. /**
  34. * 计算top 100的数。
  35. *
  36. * 计算方法如下: 1. 初始化一个top 100的数组,数值都为0,作为当前的top 100. 2. 将这个当前的top
  37. * 100数组依次与每个线程产生的top 100数组比较,调整当前top 100的值。
  38. *
  39. */
  40. private Integer[] populateTop100() {
  41. Integer[] top100 = new Integer[100];
  42. for (int i = 0; i < 100; i++) {
  43. top100[i] = new Integer(0);
  44. }
  45. for (int i = 0; i < 10; i++) {
  46. try {
  47. adjustTop100(top100, completionService.take().get());
  48. } catch (InterruptedException e) {
  49. e.printStackTrace();
  50. } catch (ExecutionException e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. return top100;
  55. }
  56. /**
  57. * 将当前top 100数组和一个线程返回的top 100数组比较,并调整当前top 100数组的数据。
  58. */
  59. private void adjustTop100(Integer[] currentTop100, Integer[] subTop100) {
  60. Integer[] currentTop200 = new Integer[200];
  61. System.arraycopy(currentTop100, 0, currentTop200, 0, 100);
  62. System.arraycopy(subTop100, 0, currentTop200, 100, 100);
  63. Arrays.sort(currentTop200);
  64. for (int i = 0; i < currentTop100.length; i++) {
  65. currentTop100[i] = currentTop200[currentTop200.length - i - 1];
  66. }
  67. }
  68. /**
  69. * 关闭 executor
  70. */
  71. public void shutdown() {
  72. exec.shutdown();
  73. }
  74. /**
  75. * 返回可以用的处理器个数
  76. */
  77. private int populateAvailableProcessors() {
  78. return Runtime.getRuntime().availableProcessors();
  79. }
  80. }

使用Callable,Future计算结果 

Java代码  收藏代码

  1. package my.concurrent.demo;
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import java.util.concurrent.ExecutionException;
  6. import java.util.concurrent.ExecutorService;
  7. import java.util.concurrent.Executors;
  8. import java.util.concurrent.Future;
  9. import java.util.concurrent.FutureTask;
  10. public class ConcurrentCalculator2 {
  11. private List<Future<Integer[]>> tasks = new ArrayList<Future<Integer[]>>();
  12. private ExecutorService exec;
  13. private int availableProcessors = 0;
  14. public ConcurrentCalculator2() {
  15. /*
  16. * 获取可用的处理器数量,并根据这个数量指定线程池的大小。
  17. */
  18. availableProcessors = populateAvailableProcessors();
  19. exec = Executors.newFixedThreadPool(availableProcessors);
  20. }
  21. /**
  22. * 获取10000个随机数中top 100的数。
  23. */
  24. public Integer[] top100(int[] values) {
  25. /*
  26. * 用十个线程,每个线程处理1000个。
  27. */
  28. for (int i = 0; i < 10; i++) {
  29. FutureTask<Integer[]> task = new FutureTask<Integer[]>(
  30. new Calculator(values, i * 1000, i * 1000 + 1000 - 1));
  31. tasks.add(task);
  32. if (!exec.isShutdown()) {
  33. exec.submit(task);
  34. }
  35. }
  36. shutdown();
  37. return populateTop100();
  38. }
  39. /**
  40. * 计算top 100的数。
  41. *
  42. * 计算方法如下: 1. 初始化一个top 100的数组,数值都为0,作为当前的top 100. 2. 将这个当前的top
  43. * 100数组依次与每个Task产生的top 100数组比较,调整当前top 100的值。
  44. *
  45. */
  46. private Integer[] populateTop100() {
  47. Integer[] top100 = new Integer[100];
  48. for (int i = 0; i < 100; i++) {
  49. top100[i] = new Integer(0);
  50. }
  51. for (Future<Integer[]> task : tasks) {
  52. try {
  53. adjustTop100(top100, task.get());
  54. } catch (InterruptedException e) {
  55. // TODO Auto-generated catch block
  56. e.printStackTrace();
  57. } catch (ExecutionException e) {
  58. // TODO Auto-generated catch block
  59. e.printStackTrace();
  60. }
  61. }
  62. return top100;
  63. }
  64. /**
  65. * 将当前top 100数组和一个线程返回的top 100数组比较,并调整当前top 100数组的数据。
  66. */
  67. private void adjustTop100(Integer[] currentTop100, Integer[] subTop100) {
  68. Integer[] currentTop200 = new Integer[200];
  69. System.arraycopy(currentTop100, 0, currentTop200, 0, 100);
  70. System.arraycopy(subTop100, 0, currentTop200, 100, 100);
  71. Arrays.sort(currentTop200);
  72. for (int i = 0; i < currentTop100.length; i++) {
  73. currentTop100[i] = currentTop200[currentTop200.length - i - 1];
  74. }
  75. }
  76. /**
  77. * 关闭executor
  78. */
  79. public void shutdown() {
  80. exec.shutdown();
  81. }
  82. /**
  83. * 返回可以用的处理器个数
  84. */
  85. private int populateAvailableProcessors() {
  86. return Runtime.getRuntime().availableProcessors();
  87. }
  88. }

测试包括了三部分: 
1. 没有用Executor框架,用Arrays.sort直接计算,并从后往前取100个数。 
2. 使用CompletionService计算结果 
3. 使用Callable和Future计算结果 

测试代码如下: 

Java代码  收藏代码

  1. package my.concurrent.demo;
  2. import java.util.Arrays;
  3. public class Test {
  4. private static final String FILE_PATH = "D:\\RandomNumber.txt";
  5. public static void main(String[] args) {
  6. test();
  7. }
  8. private static void test() {
  9. /*
  10. * 如果随机数已经存在文件中,可以不再调用此方法,除非想用新的随机数据。
  11. */
  12. //generateRandomNbrs();
  13. process1();
  14. process2();
  15. process3();
  16. }
  17. private static void generateRandomNbrs() {
  18. RandomUtil.generatedRandomNbrs(FILE_PATH);
  19. }
  20. private static void process1() {
  21. long start = System.currentTimeMillis();
  22. System.out.println("没有使用Executor框架,直接使用Arrays.sort获取top 100");
  23. printTop100(populateTop100(RandomUtil.populateValuesFromFile(FILE_PATH)));
  24. long end = System.currentTimeMillis();
  25. System.out.println((end - start) / 1000.0);
  26. }
  27. private static void process2() {
  28. long start = System.currentTimeMillis();
  29. System.out.println("使用ExecutorCompletionService获取top 100");
  30. ConcurrentCalculator calculator = new ConcurrentCalculator();
  31. Integer[] top100 = calculator.top100(RandomUtil
  32. .populateValuesFromFile(FILE_PATH));
  33. for (int i = 0; i < top100.length; i++) {
  34. System.out.println(String.format("top%d = %d", (i + 1), top100[i]));
  35. }
  36. long end = System.currentTimeMillis();
  37. System.out.println((end - start) / 1000.0);
  38. }
  39. private static void process3() {
  40. long start = System.currentTimeMillis();
  41. System.out.println("使用FutureTask 获取top 100");
  42. ConcurrentCalculator2 calculator2 = new ConcurrentCalculator2();
  43. Integer[] top100 = calculator2.top100(RandomUtil
  44. .populateValuesFromFile(FILE_PATH));
  45. for (int i = 0; i < top100.length; i++) {
  46. System.out.println(String.format("top%d = %d", (i + 1), top100[i]));
  47. }
  48. long end = System.currentTimeMillis();
  49. System.out.println((end - start) / 1000.0);
  50. }
  51. private static int[] populateTop100(int[] values) {
  52. Arrays.sort(values);
  53. int[] top100 = new int[100];
  54. int length = values.length;
  55. for (int i = 0; i < 100; i++) {
  56. top100[i] = values[length - 1 - i];
  57. }
  58. return top100;
  59. }
  60. private static void printTop100(int[] top100) {
  61. for (int i = 0; i < top100.length; i++) {
  62. System.out.println(String.format("top%d = %d", (i + 1), top100[i]));
  63. }
  64. }
  65. }

测试结果如下: 

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。