Home : Course Map : Chapter 8 : Java :
Demo: Task Splitting
JavaTech
Course Map
Chapter 8

Introduction
Threads Overview
  Demo 1   Demo 2
Stopping Threads
Multi-Processing
Thread Tasks
Animations
 
 Demo 3   Demo 4  
  Demo 5

Non-interacting
  Demo 6

Task Splitting
  Demo 7

Exclusivity
  Demo 8

Communicating
  Demo 9

Priority/Scheduling
More Thread

Exercises

    Supplements
Java2D Animation
  Demo 1 
Processor View
More Concurrency
Cloning
  Demo 2  Demo 3 

     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

The next level in complexity is to have multiple threads working on the same problem but on separate, non-interfering parts of the problem.

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 ranges of the numbers between 1 and that value.

Below we give another example in which four instances of the MatHunter class, a subclass of Thread, examine the quadrants of a matrix in search of the number of matrix elements with non-zero values.

Here we use the Outputable interface so that the print statements in IntCounter send their strings to the JTextArea in the applet interface.

TaskSplitApplet.java
+ Outputable.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
  * Count the number of non-zero elements in a matrix by
  * assigning instances of the MatHunter class to search
  * each quadrant.
 **/
public class TaskSplitApplet extends JApplet
             implements Outputable, ActionListener
{
  // A Swing textarea for display of string info
  JTextArea fTextArea;

  /**
    * Create a User Interface with a textarea with scroll bars
    * and a Go button to initiate processing and a Clear button
    * to clear the textarea.
   **/
  public void init () {
    Container content_pane = getContentPane ();
    JPanel panel = new JPanel (new BorderLayout ());

    // Create a text area.
    fTextArea = new JTextArea ();

    // Make it editable
    fTextArea.setEditable (false);

    // Add to a scroll pane so that a long list of
    // computations can be seen.
    JScrollPane area_scroll_pane = new JScrollPane (fTextArea);

    panel.add (area_scroll_pane,BorderLayout.CENTER);

    JButton go_button = new JButton ("Go");
    go_button.addActionListener (this);

    JButton clear_button = new JButton ("Clear");
    clear_button.addActionListener (this);

    JPanel control_panel = new JPanel ();
    control_panel.add (go_button);
    control_panel.add (clear_button);

    panel.add (control_panel,BorderLayout.SOUTH);

    // Add text area & control panel.
    content_pane.add (panel);
    
  } // init

  /** Respond to the buttons to start the threads or to clear
    * the text area.
   **/
  public void actionPerformed (ActionEvent e) {
    if (e.getActionCommand ().equals ("Go"))
        start ();
    else
        fTextArea.setText (null);
  } // actionPerformed

  /** Create 4 MatHunter threads to scan sections of the
    * matrix for non-zero elements.
   **/
  public void start () {
    int [][] intMat = new int[2000][2000];

    // Fill matrix elements with either 0 or 1 randomly chosen.
    for (int i=0; i<2000; i++) {
      for (int j=0; j<2000; j++) {
        if (Math.random () >0.5) intMat[i][j] = 1;
      }
    }

    // Create a MatHunter for each quadrant of the matrix
    MatHunter mh1 = new MatHunter (intMat,0,999,0,999,this);
    MatHunter mh2 = new MatHunter (intMat,0,999,1000,1999,this);
    MatHunter mh3 = new MatHunter (intMat,1000,1999,0,999,this);
    MatHunter mh4 = new MatHunter (intMat,1000,1999,1000,1999,this);

    println ("Start:");
    mh1.start ();
    mh2.start ();
    mh3.start ();
    mh4.start ();
  } // start

  /** Overided Outputable println to send string to text area.**/
  public void println (String str)  {
    fTextArea.append (str + CR);
  }

  /** Overided Outputable print to send string to text area.**/
  public void print (String str) {
    fTextArea.append (str);
  }
} // class TaskSplitApplet

/** Thread class to count the number of non-zero elements
  * in a section 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 [][] int_mat,
            int i1,int i2,int j1, int j2,
            Outputable out) {

    fIlo=i1; fIhi=i2;
    fJlo=j1; fJhi=j2;
    fMatrix = int_mat;
    fOutput = out;
  } // ctor

  /** Scan a section of a 2-D 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 ();
    }

    fOutput.println ("  # ones = " + fOnes + " for i = "+
        fIlo +" to " + fIhi + " & j = " + fJlo +" to " + fJhi);
  } // run

} // class MatHunter

 

Here again you will often see different threads finishing in different order as you re-run the program.

References & Web Resources

 

Latest update: Nov. 6, 2004

              Tech
Timers
  Demo 1
Hist. Adapt Range
  Demo 2
Sorting in Java
  Demo 3
Histogram Median
  Demo 4
Refactoring
  Demo 5
Error Bars
  Demo 6
Exercises

           Physics
Least Squares Fit
  Demo 1
Fit to Polynomial
  Demo 2
Fit Hist Errors
  Demo 3
Discretization
  Demo 4
Timing
  Demo 5
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.