Create Lightweight Heavyweight Threads


Create Lightweight Heavyweight Threads

Summary: In this tutorial "Create Lightweight Heavyweight Threads", you will create both lightweight and heavyweight threads in simple terms, programs and screenshots.

We know earlier, the meaning of heavyweight and lightweight threads in in Java Thread Basics with figures. Now, let us see how to create them.

1. Creating Heavyweight Threads

We know earlier, multithreading is nothing but executing multiple threads simultaneously. In the following program, two threads of different classes, Test1 and Test2 are created and executed. One thread prints the numbers in ascending order and the other in descending order, alternatively. As these threads belong to two different classes, it is an example of heavyweight process.

class Test1 extends Thread  
{
  public void run()   
  {
    for(int i=0; i<10;  i++)   
    {
      System.out.println("Test1: " + i);
      try  
      {
	Thread.sleep(1000);
      }
      catch(InterruptedException e)  
      { 
        e.printStackTrace();  
      }
    }    
  }   
}
class Test2 extends Thread   
{
  public void run()   
  {
    for(int i=9; i>=0; i--)   
    {
      System.out.println("Test2: " + i);
      try  
      {
        Thread.sleep(1000);
      }
      catch(InterruptedException e)  
      { 
        e.printStackTrace();  
      }
    }     
  }     
 }
 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 )  
     { 
       e.printStackTrace(); 
     }
   }    
}               

Create Lightweight Heavyweight Threads

The t1 prints 0 and becomes inactive for 1000 milliseconds by calling sleep() method. As the microprocessor does not have any work (or idle), it allocates its time to the waiting thread t2. t2 prints 9 and goes for sleep for 1000 milliseconds. Meantime, t1 comes out of sleep time, becomes active, prints 1 and again goes for sleep. Then t2 awakes, prints 8 and goes for sleep. Like this, the two loops managed by two threads (belonging to two different processes), t1 and t2, print the numbers alternatively. At any time given, only one thread is active and all the remaining are inactive. You can change the sleep timings and find the difference in output.

Create Lightweight Heavyweight Threads

Observe, when t1 is active, t2 is inactive and when t2 is active, t1 is inactive. sleep() method is the easiest way, a programmer can shift the execution control from one thread to the other. Other methods also exist, but to activate an inactive thread, it requires an extra method call; this we get later.

Note : At different times of execution, you may see t2 starts first even though t1 is started first. It wholly depends on your processor speed and time availability.

t1.join();

One thread creates the other. The first thread, implicitly created and executed at the beginning of the process, is main thread. For us, main() is a method, but internally it is a thread. Do not get confused, there is a thread group on the name of main; this we get later. In the above program, main thread created t1 and t2 threads. main thread is known as parent thread and t1 and t2 are known as child threads. Here, the parent thread is main and it need not be the main, it can be another thread also. In multithreaded programming, the programmer should see that child thread dies first and then its creator, parent thread. If not, t1 and t2 become orphan threads and output may differ (again depends on the processor speed). Then, how to make the parent thread to die always later than the child. Call simply join() method on the child thread. join() method is an instruction to the JVM to see that parent thread should not be allowed to die before child dies, even if the parent thread completes its job early.

e.printStackTrace();

It is another style of printing the system defined exception message.

10 thoughts on “Create Lightweight Heavyweight Threads”

  1. sir,

    this same program am getting the error as “class test1 is public it should be declared in its own file” where am going wrong?? Could u please explain

  2. sir i cant understand if parent thread dies before child thread how there output changes as thread are independent to each other

      1. sir then can you please tell me that what type of role this relationship plays if parent thread dies before child thread

        1. See this program:

          Multithreading – join( ) Example

          join( ) method makes the thread to wait until other threads finish their task.

          Generally, threads are designed to run independently of the other. join( ) method involves two threads. The invocation of join causes the currently executing thread to suspend execution until target thread finished its execution. The following is the method signature:

          public final void join( ) throws InterruptedException

          join( ) method is overloaded. The difference between join( ) and wait( ) is join( ) method does not involve in synchronization( that is, no locking of data). wait( ) method is used by JVM in thread synchronization. Other way, join( ) and wait( ) methods are used in thread communication.
          The calling thread waits until called thread completes its execution and dies. By using join( ), data consistency can be maintained.
          The following example illustrates:

          Aim: to observe the effect of join( ) method in data inconsistency( in output ).

          class NewThread implements Runnable {
          String name ; // name of a thread
          Thread t ;
          NewThread( String threadname ) {
          name = threadname ;
          t = new Thread( this, name ) ;
          System.out.println(“New thread: ” + t ) ;
          t.start();
          }
          public void run( ) {
          try {
          for( int i = 2 ; i > 0 ; i – – ) {
          System.out.println( name + “: ” + i ) ;
          Thread.sleep(1000);
          }
          }
          catch( InterruptedException e ) {
          e.printStackTrace( ) ;
          }
          System.out.println( name + ” exiting” ) ;
          }
          }
          public class JoinDemo {
          public static void main( String args[ ] ) {
          NewThread ob1 = new NewThread( “One” ) ;
          NewThread ob2 = new NewThread( “Two” ) ;
          NewThread ob3 = new NewThread( “Three” ) ;

          System.out.println( “Thread One is alive: ” + ob1.t.isAlive( ) ) ;
          System.out.println( “Thread Two is alive: ” + ob2.t.isAlive( ) ) ;
          System.out.println( “Thread Three is alive: ” + ob3.t.isAlive( ) ) ;

          try {
          System.out.println( “Waiting for threads to finish.” ) ;
          ob1.t.join( ) ; ob2.t.join( ) ; ob3.t.join( ) ;
          }
          catch( InterruptedException e ) {
          e.printStackTrace( ) ;
          }
          System.out.println( “Thread One is alive: ” + ob1.t.isAlive( ) ) ;
          System.out.println( “Thread Two is alive: ” + ob2.t.isAlive( ) ) ;
          System.out.println( “Thread Three is alive: ” + ob3.t.isAlive( ) ) ;
          System.out.println( “Main thread is exiting” ) ;
          }
          }

          Typical output when join( ) exists:
          One: 2
          New thread: Thread[Two,5,main]
          New thread: Thread[Three,5,main]
          Two: 2
          Thread One is alive: true
          Three: 2
          Thread Two is alive: true
          Thread Three is alive: true
          Waiting for threads to finish.
          One: 1
          Two: 1
          Three: 1
          One exiting
          Two exiting
          Three exiting
          Thread One is alive: false
          Thread Two is alive: false
          Thread Three is alive: false
          Main thread is exiting

          Typical output when join( ) kept in comments:

          New thread: Thread[ One,5,main ]
          New thread: Thread[ One,5,main ]
          New thread: Thread[ Two,5,main ]
          One: 2
          Two: 2
          New thread: Thread[ Three,5,main ]
          Thread One is alive: true
          Thread Two is alive: true
          Three: 2
          Thread Three is alive: true
          Thread One is alive: true
          Thread Two is alive: true
          Thread Three is alive: true
          Main thread is exiting
          One: 1
          Two: 1
          Three: 1
          One exiting
          Two exiting
          Three exiting

          In the above example, with join( ) method, main( ) method( the calling thread of ob1, ob2 and ob3 ) waits until ob1, ob2 and ob3( called threads) executes their run method. That is why second set of isAlive( ) methods prints false. main( ) method is executed at last.

          When join( ) method is kept in comments, main( ) method exits even before ob1, ob2 and ob3 perform their tasks. When calling thread terminates first, the called threads are in a state of inconsistency and prints erratic results. In the above example, both sets of isAlive( ) method prints true.

Leave a Comment

Your email address will not be published.