Exemplo n.º 1
0
  /**
   * Main method of the example
   *
   * @param args
   */
  public static void main(String[] args) {

    // Create a list of products
    ProductListGenerator generator = new ProductListGenerator();
    List<Product> products = generator.generate(10000);

    // Craete a task
    Task task = new Task(products, 0, products.size(), 0.20);

    // Create a ForkJoinPool
    ForkJoinPool pool = new ForkJoinPool();

    // Execute the Task
    pool.execute(task);

    // Write information about the pool
    do {
      System.out.printf("Main: Thread Count: %d\n", pool.getActiveThreadCount());
      System.out.printf("Main: Thread Steal: %d\n", pool.getStealCount());
      System.out.printf("Main: Paralelism: %d\n", pool.getParallelism());
      try {
        TimeUnit.MILLISECONDS.sleep(5);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    } while (!task.isDone());

    // Shutdown the pool
    pool.shutdown();

    // Check if the task has completed normally
    if (task.isCompletedNormally()) {
      System.out.printf("Main: The process has completed normally.\n");
    }

    // Expected result: 12. Write products which price is not 12
    for (int i = 0; i < products.size(); i++) {
      Product product = products.get(i);
      if (product.getPrice() != 12) {
        System.out.printf("Product %s: %f\n", product.getName(), product.getPrice());
      }
    }

    // End of the program
    System.out.println("Main: End of the program.\n");
  }
Exemplo n.º 2
0
 static void test(ForkJoinPool pool, int num) throws Exception {
   int ps = pool.getParallelism();
   long start = System.nanoTime();
   DynamicFib f = new DynamicFib(num);
   pool.invoke(f);
   long time = System.nanoTime() - start;
   double secs = ((double) time) / NPS;
   long result = f.number;
   System.out.print("DynamicFib " + num + " = " + result);
   System.out.printf("\tTime: %9.3f", secs);
   long sc = pool.getStealCount();
   long ns = sc - lastStealCount;
   lastStealCount = sc;
   System.out.printf(" Steals: %4d", ns / ps);
   System.out.printf(" Workers: %4d", pool.getPoolSize());
   System.out.println();
 }
Exemplo n.º 3
0
 // 16、实现showLog()方法,接受一个ForkJoinPool对象作为参数,输出关于它的状态信息及线程、任务的执行信息
 private static void showLog(ForkJoinPool pool) {
   System.out.printf("**********************\n");
   System.out.printf("Main: Fork/Join Pool log\n");
   System.out.printf("Main: Fork/Join Pool: Parallelism: %d\n", pool.getParallelism());
   System.out.printf("Main: Fork/Join Pool: Pool Size: %d\n", pool.getPoolSize());
   System.out.printf(
       "Main: Fork/Join Pool: Active Thread Count: %d\n", pool.getActiveThreadCount());
   System.out.printf(
       "Main: Fork/Join Pool: Running Thread Count: %d\n", pool.getRunningThreadCount());
   System.out.printf(
       "Main: Fork/Join Pool: Queued Submission: %d\n", pool.getQueuedSubmissionCount());
   System.out.printf("Main: Fork/Join Pool: Queued Tasks: %d\n", pool.getQueuedTaskCount());
   System.out.printf(
       "Main: Fork/Join Pool: Queued Submissions: %s\n", pool.hasQueuedSubmissions());
   System.out.printf("Main: Fork/Join Pool: Steal Count: %d\n", pool.getStealCount());
   System.out.printf("Main: Fork/Join Pool: Terminated : %s\n", pool.isTerminated());
   System.out.printf("**********************\n");
 }
Exemplo n.º 4
0
  public static int[] sort(int[] input) {
    ForkJoinPool mainPool = new ForkJoinPool();
    int[] output = new int[input.length];

    // from round 0...n, segment length is 2^n.
    int round = (int) Math.ceil((Math.log(input.length) / Math.log(2)));

    for (int i = 3; i < round; i++) {
      // minimal length=16
      int segmentLen = 1 << i;
      mergeRound(segmentLen, input, output, mainPool);
      int[] temp = input;
      input = output;
      output = temp;
    }
    System.out.println("\n\tthread account: " + mainPool.getActiveThreadCount());
    System.out.println("\tparallelism: " + mainPool.getParallelism());
    System.out.println("\tsteal count: " + mainPool.getStealCount());
    mainPool.shutdown();
    return input;
  }
Exemplo n.º 5
0
  public static void main(String[] args) {

    // одна из идей - работает как аккумулятор

    // T reduce(T identity, BinaryOperator<T> accumulator);
    // Первый Reduce метод
    // определяем самого старшего человека
    // Reduce метод принимает функцию аккумулятора BinaryOperator. Это на самом деле BiFunction,
    // когда оба операнда
    // имеют один и тот же тип, в этом случае Person. BiFunctions похожи на Function, но принимает
    // два аргумента.
    // Пример функции сравнивает людей по возрасту и возвращает самого старшего.
    persons.stream().reduce((p1, p2) -> p1.age > p2.age ? p1 : p2).ifPresent(System.out::println);

    // Optional<T> reduce(BinaryOperator<T> accumulator);
    // Второй Reduce метод принимает идентифицирующее значение и BinaryOperator. Этот метод может
    // быть использован
    // для «создания» нового человека с агрегированным имен и возрастом других человек в потоке:
    BinaryOperator<Person> binaryOperator =
        (p1, p2) -> {
          p1.age += p2.age;
          p1.name += p2.name;
          return p1;
        };

    Person result = persons.stream().reduce(new Person("", 0), binaryOperator);

    // Третий Reduce
    // <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U>
    // combiner);
    // Третий Reduce  метод принимает три параметра: значение идентификатора,BiFunction аккумулятор
    // и объединитель
    // функции типа BinaryOperator. Поскольку идентифицирующее значение не ограничивает тип Person,
    // мы можем
    // использовать это сокращение для определения суммы возрасте от всех лиц:
    Integer ageSumm =
        persons
            .stream()
            .reduce(
                0,
                (sum, p) -> sum += p.age, // accumulator
                (sum1, sum2) -> sum1 + sum2 // combiner
                );
    System.out.println(ageSumm);

    Integer ageSum1 =
        persons
            .parallelStream()
            .reduce(
                0,
                (sum, p) -> {
                  System.out.format("accumulator: sum=%s; person=%s\n", sum, p);
                  return sum += p.age;
                },
                (sum1, sum2) -> {
                  System.out.format("combiner: sum1=%s; sum2=%s\n", sum1, sum2);
                  return sum1 + sum2;
                });

    persons
        .parallelStream()
        .reduce(
            0,
            (sum, p) -> {
              System.out.format(
                  "accumulator: sum=%s; person=%s [%s]\n",
                  sum, p, Thread.currentThread().getName());
              return sum += p.age;
            },
            (sum1, sum2) -> {
              System.out.format(
                  "combiner: sum1=%s; sum2=%s [%s]\n",
                  sum1, sum2, Thread.currentThread().getName());
              return sum1 + sum2;
            });

    ForkJoinPool commonPool = ForkJoinPool.commonPool();
    System.out.println(commonPool.getParallelism());

    List<String> stringList =
        Stream.of("dd2", "aa2", "bb1", "bb3", "cc4")
            .filter(
                s -> {
                  System.out.println("Фильтр: " + s);
                  return s.startsWith("bb");
                })
            .collect(Collectors.toList());

    Stream.of("dd2", "aa2", "bb1", "bb3", "cc4")
        .map(
            s -> {
              System.out.println("map: " + s);
              return s.toUpperCase();
            })
        .anyMatch(
            s -> {
              System.out.println("anyMatch: " + s);
              return s.startsWith("A");
            });

    // о-первых, операция сортировки выполняется на всей совокупности входных данных. Другими
    // словами, sorted
    // выполнен в горизонтальном направлении. Таким образом, sorted вызывается 8 раз
    // для нескольких комбинаций на каждом элементе во входной коллекции.
    Stream.of("dd2", "aa2", "bb1", "bb3", "cc4")
        .sorted(
            (s1, s2) -> {
              System.out.printf("sort: %s; %s\n", s1, s2);
              return s1.compareTo(s2);
            })
        .filter(
            s -> {
              System.out.println("filter: " + s);
              return s.startsWith("a");
            })
        .map(
            s -> {
              System.out.println("map: " + s);
              return s.toUpperCase();
            })
        .forEach(s -> System.out.println("forEach: " + s));

    // после оптимизации
    Stream.of("dd2", "aa2", "bb1", "bb3", "cc4")
        .filter(
            s -> {
              System.out.println("filter: " + s);
              return s.startsWith("a");
            })
        .sorted(
            (s1, s2) -> {
              System.out.printf("sort: %s; %s\n", s1, s2);
              return s1.compareTo(s2);
            })
        .map(
            s -> {
              System.out.println("map: " + s);
              return s.toUpperCase();
            })
        .forEach(s -> System.out.println("forEach: " + s));

    // filter:  dd2
    // filter:  aa2
    // filter:  bb1
    // filter:  bb3
    // filter:  cc4
    // map:     aa2
    // forEach: AA2

    Supplier<Stream<String>> streamSupplier =
        () -> Stream.of("dd2", "aa2", "bb1", "bb3", "cc").filter(s -> s.startsWith("a"));

    streamSupplier.get().anyMatch(s -> true); // операция пройдет успешно
    streamSupplier.get().noneMatch(s -> true); // здесь также все будет ok
  }
Exemplo n.º 6
0
 /** getParallelism returns size set in constructor */
 public void testGetParallelism() {
   ForkJoinPool p = new ForkJoinPool(1);
   try (PoolCleaner cleaner = cleaner(p)) {
     assertEquals(1, p.getParallelism());
   }
 }