Java Reference
In-Depth Information
private
private class
class ThreadPoolExecutorTask
ThreadPoolExecutorTask implements
implements Callable < Integer > {
private
private int
int first ;
private
private int
int last ;
public
public ThreadPoolExecutorTask ( int
int first , int
int last ) {
this
this . first = first ;
this
this . last = last ;
}
public
public Integer call () {
int
int subCount = 0 ;
for
for ( int
int i = first ; i <= last ; i ++) {
iif ( d [ i ] < 0.5 ) {
subCount ++;
}
}
return
return subCount ;
}
}
public
public static
void main ( String [] args ) {
d = createArrayOfRandomDoubles ();
ThreadPoolExecutor tpe = new
static void
new ThreadPoolExecutor ( 4 , 4 ,
Long . MAX_VALUE ,
TimeUnit . SECONDS ,
new
new LinkedBlockingQueue ());
Future [] f = new
new Future [ 4 ];
int
int size = d . length / 4 ;
for
for ( int
int i = 0 ; i < 3 ; i ++) {
f [ i ] = tpe . submit (
new
new ThreadPoolExecutorTask ( i * size , ( i + 1 ) * size - 1 );
}
f [ 3 ] = tpe . submit ( new
new ThreadPoolExecutorTask ( 3 * size , d . length - 1 );
int
int n = 0 ;
for
for ( int
int i = 0 ; i < 4 ; i ++) {
n += f . get ();
}
System . out . println ( "Found " + n + " values" );
}
}
On a four-CPU machine, this code will fully utilize all available CPUs, processing the array
in parallel while avoiding creating and queuing the 2 million tasks used by the fork/join ex-
ample. The performance is predictably faster, as Table 9-4 shows.
Search WWH ::




Custom Search