示例#1
0
  private static void slowExample(WorkerPool workerPool, int nTasks) {
    List<Callable<Integer>> taskList = new ArrayList<Callable<Integer>>();
    Random random = new Random();
    int maxWait = 10000;
    for (int i = 1; i <= nTasks; i++) {
      final int wait = random.nextInt(maxWait);
      Callable<Integer> callable =
          new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
              Thread.sleep(wait);
              return wait;
            }
          };
      taskList.add(callable);
    }

    long start = System.currentTimeMillis();
    List<Integer> waits = workerPool.invokeAll(taskList);
    long finish = System.currentTimeMillis();

    int longestWait = 0;
    int totalWait = 0;
    for (int wait : waits) {
      longestWait = wait > longestWait ? wait : longestWait;
      totalWait += wait;
    }
    System.out.println(
        String.format(
            "elapsed time: %5d ms (%.2f%%)",
            finish - start, 100 * (1.0 * (finish - start)) / totalWait));
    System.out.println(String.format("longest wait: %5d ms", longestWait));
    System.out.println(String.format("average wait: %5d ms", totalWait / nTasks));
    System.out.println(String.format("total wait:   %5d ms", totalWait));
  }
示例#2
0
  /**
   * Return strings including the integers -1 through -10.
   *
   * @param workerPool
   */
  private static void listExample(WorkerPool workerPool) {
    List<Callable<String>> taskList = new ArrayList<Callable<String>>();
    for (int i = 1; i <= 10; i++) {
      final String input = Integer.toString(-1 * i);
      Callable<String> callable =
          new Callable<String>() {
            @Override
            public String call() throws Exception {
              // do all your parallelizable work here
              return "R(" + input + ")";
            }
          };
      taskList.add(callable);
    }

    List<String> resultList = workerPool.invokeAll(taskList);

    for (String result : resultList) {
      System.out.println("result: " + result);
    }
  }
示例#3
0
  /**
   * Calculate the squares of the integers 1 through 10.
   *
   * @param workerPool
   */
  private static void mapExample(WorkerPool workerPool) {
    Map<Integer, Callable<Integer>> taskMap = new HashMap<Integer, Callable<Integer>>();
    for (int i = 1; i <= 10; i++) {
      final int input = i;
      Callable<Integer> callable =
          new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
              // do all your parallelizable work here
              return input * input;
            }
          };
      taskMap.put(i, callable);
    }

    Map<Integer, Integer> resultMap = workerPool.invokeAll(taskMap);

    for (Map.Entry<Integer, Integer> entry : resultMap.entrySet()) {
      System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
    }
  }