Java Reference
In-Depth Information
8.5.2 Task splitting
The next level in complexity involves multiple threads working on the same
problem but on separate, non-interfering parts. For example, given a particular
integer value, a program could find the number of primes up to that value by
using different threads to work on different sections of the range between 1 and
the specified value.
In the example here, we use the task-splitting technique to scan a matrix. The
snippet below shows a class that searches a matrix and counts the number of
positive non-zero elements:
/**
* Thread class to count the number of non-zero elements
*inasection of a matrix.
**/
class MatHunter extends Thread
{
int [][] fMatrix;
int fIlo, fIhi, fJlo, fJhi;
int fOnes=0;
Outputable fOutput;
/** Constructor gets the matrix and the indices specifying
* what section to examine.
**/
MatHunter (
int [][] imat,
int i1, int i2, int j1, int j2,
Outputable out
) {
fIlo = i1; fIhi = i2;
fJlo = j1; fJhi = j2;
fMatrix = imat;
fOutput = out;
} // ctor
/** Examine a section of a 2D matrix and
* count the number of non-zero elements.
**/
public void run () {
for (int i=fIlo; i <= fIhi; i++) {
for (int j=fJlo; j <= fJhi; j++) {
if (fMatrix[i][j] > 0) fOnes++;
}
yield ();
 
Search WWH ::




Custom Search