Multiple threads Heavyweight Process


Multiple threads Heavyweight Process

Summary: By the time you complete this tutorial "Multiple threads Heavyweight Process", you will be comfortable to create multiple threads of heavyweight executing alternatively.

We know earlier how to create single threads by extending Thread class and also by implementing Runnable interface. Now let us create multiple threads of different processes and execute them. Before going further, let us know what is lightweight process and heavyweight process. It is very necessary in multiple threads execution.

What is Lightweight process and Heavyweight process?

Advantage of multithreading is to reduce the microprocessor’s idle time so that the response to the user gets earlier.

If the execution control is shifted between the threads of the same process it is known as lightweight process and if the control is shifted between the threads of the different process, it is known as heavyweight process.

As you can guess, the lightweight process has more performance than heavyweight process. Generally, threads are designed to be lightweight process.

Multiple threads Heavyweight Process

The following program is an example on heavyweight process wherein two threads t1 and t2 of two different processes of Test1 and Test2 are created executed simultaneously. If t1 is blocked (or stopped or inactive) its execution, the t2 execution starts and similarly if t2 stops its execution, t1 starts (active).

Aim: To create two threads of different classes (heavyweight process) that prints 0 to 99 and 99 to 0 alternatively.

class Test1 extends Thread                       // prints 0 to 99
{
  public void run()
  {
    for(int i = 0; i < 100; i++)
    {
      System.out.println("Test1: " + i);
      try
      {
        Thread.sleep(1000);
      }
      catch(InterruptedException e)
      {
        System.out.println("Some problem. " + e);
      }
    }
  }
}

class Test2 extends Thread                       // prints 99 to 0
{
  public void run()
  {
    for( int i = 99; i >= 0; i--)
    {
      System.out.println("Test2: " + i);
      try
      {
        Thread.sleep(1000);
      }
      catch(InterruptedException e)
      {
        System.out.println("Some problem. " + e);
      }
    }
  }
}

public class TwoRuns
{
  public static void main(String args[])
  {
    Test1 t1 = new Test1();
    Test2 t2 = new Test2();

    t1.start();
    t2.start();
   
    try
    {
      t1.join();
      t2.join();
    }
    catch(InterruptedException e)
    {
      System.out.println("Some problem. " + e);
    }
  }
}


Multiple threads Heavyweight Process
Output screen of TwoRuns.java of Multiple threads Heavyweight Process

2 thoughts on “Multiple threads Heavyweight Process”

  1. what is the purpose of writing t1.join() and t2.join() method in the above example,if we dont write the t1.join() and t2.join() it will give same output?

Leave a Comment

Your email address will not be published.