Thread Array Java Example


Create Thread Array Example

Summary: By the end of this tutorial "Create Thread Array Example", you will be comfortable in creation of array of threads and starting them. Explained in simple terms.

After knowing how to create multiple threads (both lightweight and heavyweight), let us modify the code to suit for creation of multiple threads as an array.

Program on Create Thread Array Example

In the following code an array of 5 threads is created and started. Being lightweight, all threads call the same run() method. In the run() method, a sum value is added with i value of for loop; a simple code to get the concept of array of threads.

class Test extends Thread
{
  static int sum;
  public void run()
  {
    for(int i = 0; i < 10; i++)
    {
      sum += i;
    }		
  }
}
public class ArrayOfThreads
{
  public static void main(String args[])
  {
    Test test[] = new Test[5];  
     for(int i = 0; i < test.length; i++)
     {
       test[i] = new Test();
       test[i].start();
     }
     System.out.println("Sum = " + Test.sum);
  }
}


Thread Array Java Example
Output screen on Create Thread Array Example

Test test[] = new Test[5];

In the above statement, five threads test[0], test[1] etc. are not thread objects; they are reference variables. That is, test[] is an array of reference variables of Test class but not array objects Test class. They must be converted into array objects and this is done in the next statement.

test[i] = new Test();
test[i].start();

new Test() converts each reference variable into array object. When converted into object, start() method is called on the thread object so that it calls the callback method run().

Leave a Comment

Your email address will not be published.