Bright Java Tutorial

is brought to you by DoITBright LLC

Java

Multithreading By Extending The Thread Class

Multithreading is an execution model that allows an application or part of an application to be executed simultaneously by different users or system processes without having to execute multiple copies of the application. Let us say, you have an application that has to pull records from the database, then perform some data preparation for a more readability, then render the page to display the data. What if, the execution is still in the middle and we want to run the same set of code again? If an application is not designed to run as a multithreaded application, the next request to run the set of codes must wait till the current request being processed is finished. Another scenario might be, we are trying to generate a file for every student information that we have in the database. So, if we have atleast 10,000 students, we must generate 10,000 files. This can take a long time to accomplish depending on how huge the data for each student is. A great solution is to divide the file generation process into several set of threads. Let us say, 1,000 students per thread? This means, we will run 10 threads at the same time. This will speed up the whole process of generating the 10,000 files. In lay man's terms, you might want to hire 10 people and designate 1,000 student records for each person so they can work concurrently and the results maybe achieved faster. In Core Java, one way to accomplish this is to extend the java.lang.Thread class. Let us look at the example.

  package com.example.core.thread;

  /*
   * This class contains the core functionality of what we 
   * want to execute. Imagine the printStringArray method 
   * below as doing heavy processing stuff like making 
   * database calls and writing to a file.
   *
   * @author Rolan Liwanag
   */
  public class Main {

    public void printStringArray(String[] stringArr) {
      for(String str : stringArr) {
        System.out.println(">>> " + str);
      }
    }
  }
                            

The above code contains the set of code that we want to execute in a multithreaded manner.

  package com.example.core.thread;

  /*
   * @author Rolan Liwanag
   * 
   * This class extends java.lang.Thread which makes it 
   * possible to run multiple instance of this
   * class at the same time.
   */
  public class ThreadProcessor extends Thread {
	
    private String[] stringArr;

    public ThreadProcessor(String[] stringArr) {
      this.stringArr = stringArr;
    }
	
    /*
     * The run method is where the core processing happens
     * in a thread. The run method is invoked when the 
     * start method is invoked.
     */
    public void run(){
      Main main = new Main();
      main.printStringArray(stringArr);
    }
  }
                            

The ThreadProcessor class is a Thread because it extends the java.lang.Thread class. This thread class is responsible in executing the set of code we wish to execute.

  package com.example.core.thread;

  /**
   * This class will demonstrate how to process multiple 
   * threads simultaneously.
   * 
   * A thread is an independent path of execution within 
   * a program. Just imagine a child writing the sentence 
   * "The quick brown fox jumped over the lazy dog" 100 
   * times. If 2 children will do it at the same time, 
   * approximately at same given span of time, they will 
   * be able to write that sentence 200 times.
   * 
   * @author Rolan Liwanag
   * 
   */
  public class ThreadSpawner {

    public static void main(String[] args) {
      String[] hugeArray 
        = {"A","B","C","1","2","3","D","E","F","4"};
      int maxThreads = 4;
      int stringPerThread = 3;
		
      int totalThreads;

      //Calculate totalThreads and total Strings per Thread
      if(hugeArray.length%stringPerThread==0) {
        totalThreads = hugeArray.length/stringPerThread;
      } else {
        totalThreads = (hugeArray.length/stringPerThread)+1;
      }
		
      if(totalThreads>maxThreads){
        if(hugeArray.length%maxThreads==0){
          stringPerThread = hugeArray.length/maxThreads;
          totalThreads = maxThreads;
        }else{
          stringPerThread = hugeArray.length/maxThreads+1;
          totalThreads = maxThreads;
        }
      }

      ThreadProcessor[] xmlThreads
        = new ThreadProcessor[totalThreads];
		
      //divide the hugeArray into several array and assign 
      //each array to a thread
      int counter = 0;
      for(int i=0; i < totalThreads; i++){
        //this array will hold a part of the hugeArray
        String[] subArray = new String[stringPerThread];
        //assign some of the elements of hugeArray 
        //to subArray
        for(int j= 0; j < stringPerThread ;j++){
          if(counter == hugeArray.length){
            break;
          }
          subArray[j] = hugeArray[counter];
          counter++;
        }
        //create a thread for processing subArray
        xmlThreads[i] = new ThreadProcessor(subArray);				
      }
      //start processing the threads
      for(int j=0; j < totalThreads; j++){
        //invoke the thread run method via the start method
        xmlThreads[j].start();
        try {
          xmlThreads[j].join();
        } catch (InterruptedException e) {

        }
      }
    }
  }
                            


In our example, imagine the array hugeArray represents the student records we wish to write into a file. In the ThreadSpawner class, it divided the records and assigned each sub set of records into a thread. The threads run concurrently and each performs the same set of instructions to complete the work. The above is a good example of Java multithreading or a Java multithreaded application.


Back    Next