View Javadoc
1   /*
2    * Copyright 2024 Hochschule Luzern Informatik.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package ch.hslu.exercises.sw11.ex1.n41.array.init;
17  
18  import java.util.concurrent.RecursiveAction;
19  import java.util.concurrent.ThreadLocalRandom;
20  
21  /**
22   * Codebeispiel zu RecursiveAction für die Initialisierung eines int-Arrays.
23   */
24  @SuppressWarnings("serial")
25  public final class RandomInitTask extends RecursiveAction {
26  
27      private static final int THRESHOLD = 5;
28      private final int[] array;
29      private final int min;
30      private final int max;
31      private final int rdMax;
32  
33      /**
34       * Erzeugt einen Teil-Array-Init Task.
35       *
36       * @param array    Interger-Array.
37       * @param rndBound maximaler Random-Wert-1.
38       */
39      public RandomInitTask(final int[] array, final int rndBound) {
40          this(array, 0, array.length, rndBound);
41      }
42  
43      private RandomInitTask(final int[] array, final int min, final int max, final int rdBound) {
44          this.array = array;
45          this.min = min;
46          this.max = max;
47          this.rdMax = rdBound;
48      }
49  
50      @Override
51      protected void compute() {
52          if ((max - min) <= THRESHOLD) {
53              for (int i = min; i < max; i++) {
54                  array[i] = ThreadLocalRandom.current().nextInt(rdMax);
55              }
56          } else {
57              final int mid = min + (max - min) / 2;
58              RandomInitTask left = new RandomInitTask(array, min, mid, rdMax);
59              RandomInitTask right = new RandomInitTask(array, mid, max, rdMax);
60              invokeAll(left, right);
61          }
62      }
63  }