Java Reference
In-Depth Information
46 }
47
else
{
48
int
mid = (low + high) /
2
;
49 RecursiveTask<Integer> left =
new
MaxTask(list, low, mid);
50 RecursiveTask<Integer> right =
new
MaxTask(list, mid, high);
51
52
split into two parts
right.fork();
fork right
fork left
join tasks
53
left.fork();
54
return new
Integer(Math.max(left.join().intValue(),
55
right.join().intValue()));
56 }
57 }
58 }
59 }
The maximal number is 8999999
The number of processors is 2
Time is 44 milliseconds
Since the algorithm returns an integer, we define a task class for fork join by extending
RecursiveTask<Integer>
(lines 26-58). The
compute
method is overridden to return the
max element in a
list[low..high]
(lines 39-57). If the list is small, it is more efficient to
be solved sequentially (lines 40-46). For a large list, it is split into two halves (lines 48-50).
The tasks
left
and
right
find the maximal element in the left half and right half, respec-
tively. Invoking
fork()
on the task causes the task to be executed (lines 52 and 53). The
join()
method awaits for the task to complete and then returns the result (lines 54 and 55).
30.37
✓
✓
How do you define a
ForkJoinTask
? What are the differences between
RecursiveAction
and
RecursiveTask
?
Check
Point
30.38
How do you tell the system to execute a task?
30.39
What method can you use to test if a task has been completed?
30.40
How do you create a
ForkJoinPool
? How do you place a task into a
ForkJoinPool
?
K
EY
T
ERMS
condition 1114
deadlock 1126
fail-fast 1128
fairness policy 1113
Fork/Join Framework
multithreading 1098
race condition 1111
semaphore 1124
synchronization wrapper
1127
1128
synchronized block
1112
lock 1112
monitor
thread 1098
thread-safe
1118
1111
C
HAPTER
S
UMMARY
1.
Each task is an instance of the
Runnable
interface. A
thread
is an object that facilitates
the execution of a task. You can define a task class by implementing the
Runnable
interface and create a thread by wrapping a task using a
Thread
constructor.
2.
After a thread object is created, use the
start()
method to start a thread, and the
sleep(long)
method to put a thread to sleep so that other threads get a chance to run.
Search WWH ::
Custom Search