Threads

A thread is an independent sequential path of execution within a program. Threads running concurrently within a program use common memory space and share both data and code. They are lightweight as compared to independent process. A thread in execution has its own call stack. It can also be said that there is “one call stack per thread” or its reverse “one thread per call stack”.
The main() method that initiates the whole application, runs in a thread, called the main-thread. Thus a main call stack is also maintained by the JVM for main-thread. On the main call stack, main() is the first method at the bottom (as shown below). But as soon as you create a new thread, a new stack is created, which is separate from the main call stack, as shown in the following diagram. This new call stack runs concurrently with the main thread.
It is important to keep in mind that “threads running in parallel” does not mean that they are actually running at the same time. Since all the threads are running on a single processor, thus according to CPU scheduling, CPU switches among different threads randomly. JVM handles the switching process so rapidly that it appears that they are running concurrently. Like other threads, main is also a thread, so it is also involved in the switching process. As the threads finish their job, they come out from switching process.

Creating Threads

Implementation of threads can be achieved using the following 2 methods:
  1. By extending the "java.lang.Thread" class
  2. By implementing "java.lang.Runable" interface
  1. Extending "java.lang.Thread" Class
  2. A typical procedure for using the Thread class for creating threads in execution is as follows: A class extending the Thread class overrides the run() method from the Thread class. The run() method consists of the code to be executed by the thread. Notice that while overriding run() method, it must have public access specifier. Do not call run() method directly using the object of the derived class. The start() method, which is inherited from the Thread class should be invoked using the object of derived class, to make the class eligible for running and causes to execute run() method. You can assign user specific name to a thread by using setName() method of Thread class.
    Implementation:
    The following program shows, how to use java.lang.Thread class to create multiple threads of a class.
    class Process extends Thread
       {
        int start,end;
        Process(int s,int e,String name)
          {
           start=s; end=e;
           setName(name);
          }
        public void run()
          {
            for(int i=start;i<=end;i++)
             {
               System.out.println(“thread->”+getName()+” : “+i);
               try{
                   Thread.sleep(100);
                  }
               catch(InterruptedException ex){ex.printStackTrace();}	
             }
            System.out.println(Thread.currentThread()+ “ : thread Finished....”);	
          }
    }
    public class ExtendsThread 
     {
    	public static void main(String[] args)
    	{
    		Process thrd1=new Process(1,5,”Real”);
    		Process thrd2=new Process(6,10,”Java”);
    		thrd1.start();
    		thrd2.start();
    	}
    }
    Output:
    	thread->Java : 6
    	thread->Real : 1
    	thread->Real : 2
    	thread->Java : 7
    	thread->Real : 3
    	thread->Java : 8
    	thread->Java : 9
    	thread->Real : 4
    	thread->Java : 10
    	thread->Real : 5
    	Thread[Java,5,main] : thread Finished....
    	Thread[Real,5,main] : thread Finished....
    

    Implementing java.lang.Runnable Interface

    The other and most commonly used method of creating threads is by ­implementing java.lang.Runnable interface. This method is preferred, when the class already inherits other class, thus you can not extend java.lang.Thread class more because multiple inheritance is not allowed in Java. But a class can implement multiple interfaces.
    Runnable interface consists of one abstract method declaration:
    public interface Runnable
        {
          void run();
        }
    The following program implements Runnable interface for creating threads:
    For Example:
    class Job implements Runnable
      {	
        int start,end;
    	Job(int s,int e)
    	     { start=s; 
    	        end=e;   }
    	public void run()
    	     {
    	       for(int i=start;i<=end;i++)
    		{
    System.out.println(“thread:”+Thread.currentThread().getName()+”:“+i);
    		try{   Thread.sleep(100);	 }
    		catch(InterruptedException ex){ex.printStackTrace();}	
    		}
     System.out.println(Thread.currentThread()+ “ : thread Finished....”);	
    	 }
    }
    public class RunnableInterface 
      {  public static void main(String[] args) 
    	{		
    	Job obj1=new Job(1,3);
    	Job obj2=new Job(6,8);
    	Thread thrd1=new Thread(obj1);
    	thrd1.setName(“Real”);
    	Thread thrd2=new Thread(obj2);
    	thrd2.setName(“Java”);
    	thrd1.start();
    	thrd2.start();
    	}
     }

About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
17 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android. If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : [email protected] #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap