Java Reference
In-Depth Information
an array of
int
values, but you can modify it to become a generic method (see Programming
Exercise 30.13).
In general, a problem can be solved in parallel using the following pattern:
if (the program is small)
solve it sequentially;
else {
divide the problem into nonoverlapping subproblems;
solve the subproblems concurrently;
combine the results from subproblems to solve the whole problem;
}
Listing 30.11 develops a parallel method that finds the maximal number in a list.
L
ISTING
30.11
ParallelMax.java
1
import
java.util.concurrent.*;
2
3
public class
ParallelMax {
4
public static void
main(String[] args) {
5
// Create a list
6
final int
N =
9000000
;
7
int
[] list =
new int
[N];
8
for
(
int
i =
0
; i < list.length; i++)
9 list[i] = i;
10
11
long
startTime = System.currentTimeMillis();
12 System.out.println(
"\nThe maximal number is "
+ max(list));
13
long
endTime = System.currentTimeMillis();
14 System.out.println(
"The number of processors is "
+
15 Runtime.getRuntime().availableProcessors());
16 System.out.println(
"Time is "
+ (endTime - startTime)
17 +
" milliseconds"
);
18 }
19
20
invoke max
public static int
max(
int
[] list) {
21
RecursiveTask<Integer> task =
new
MaxTask(list,
0
, list.length);
create a
ForkJoinTask
create a
ForkJoinPool
execute a task
22
ForkJoinPool pool =
new
ForkJoinPool();
23
return
pool.invoke(task);
24 }
25
26
private static class
MaxTask
extends
RecursiveTask<Integer> {
define concrete
ForkJoinTask
27
private final static int
THRESHOLD =
1000
;
28
private int
[] list;
29
private int
low;
30
private int
high;
31
32
public
MaxTask(
int
[] list,
int
low,
int
high) {
33
this
.list = list;
34
this
.low = low;
35
this
.high = high;
36 }
37
38 @Override
39
public
Integer compute() {
40
if
(high - low < THRESHOLD) {
41
int
max = list[
0
];
42
for
(
int
i = low; i < high; i++)
43
if
(list[i] > max)
44 max = list[i];
45
perform the task
solve a small problem
return new
Integer(max);
Search WWH ::
Custom Search