Monday, 7 September 2015

Multithreading in JAVA

                     JAVA is a very powerful language which supports many features. Multi-threading & Graphics programming are only few of them. Today, I am going to discuss a very simple program to explain both these concepts. Also I will share code with you on this post as well as on my GitHub account. Lets start the discussion with Multi-threading. Multi-treading allows programmer to use computer's resources in a very efficient manner. A Multi-threaded program is one which contains 2 or more parts that can run concurrently. Each part of such program is called a Thread & it defined the separate path for execution. Now a days all modern Operating Systems supports Multitasking. Multi-tasking is basically divided into two types: Process Based &  Thread Based.

                               Process Based Multitasking is a feature which allows the computer to run 2 or more programs simultaneously. As a example, consider that I can use Browser program for surfing the internet and at the same time I may use Word Editor to edit files. So, we can say that program is the smallest unit dispatched to the processor in the Process based Multi-tasking.

                               Thread Based Multi-tasking is a feature which allows computer to run multiple functions in one program. As a example, consider that I am writing a word file in Microsoft Word. So, I can write the file & at the same time I can perform spell-check operation too. We can say that Thread is the smallest unit dispatched to the processor in the Thread Based Multi-tasking. If we compare both the types of Multi-threading then its very clear that Thread Based Multi-tasking is better as it require less overhead than Process Based. Advantage of Multitasking is to reduce idle time of CPU & to increase the performance.

                               In JAVA, we can create threads by following two methods,
  1. To extend the Thread Class. (Click to check the post)
  2. To implement Runnable Interface. (Click to check the post)
Threads are implemented  by invoking the run() method which is declared as follows. The method can be invoked by using an object of type Thread & calling the start() method.


public void run()
{
    ...
    ...
    ...
}


Before starting any program we must understand the Life Cycle of Thread, as there are many states of a thread during its life cycle.

1. Newborn State:
When we create a thread object the object is in Newborn state. At this state we can start its execution by using start() method.

2. Runnable State:
This state means thread is ready for execution & is waiting for the availability of the processor. All threads are arranged in a Queue & if all threads have same priority then they are executed on FIFO (First In First Out) criteria. However by using  yield() method, we can surrender/ give up the control of the thread & it joins the queue at the end, to wait for its turn.

3.Running State:
It means CPU/Processor has given its time to thread for execution.

4.Blocked State:
A thread is said to be Blocked if it is prevented from entering the runnable & running states. This occurs when thread is suspended, sleeping, waiting in order to satisfy certain requirements. So, a running thread may give up its control in one of the following situations, 
  1. It has been suspended using suspend() method. To revive it again & enter the runnable state, use resume() method.
  2. It has been made to sleep for a specified time using sleep(milliseconds). After specified time period thread automatically re-enters the runnable state.
  3. It has been told or asked until some event happens. This is done by using wait() method. The thread can re-enter the runnable state using notify() method.

5. Dead State:
A running thread ends its life when it completes the execution of its run() method. It is a natural death. However by using stop() method, we can cause its premature death.

                               After learning basics of Multithreading, now is the time to consider one hands-on of a program. Following is the program which makes use of Thread class. Three classes are created also three threads are created for those classes respectively. All the threads are executed simultaneously. I have attached the sample outputs but please note that outputs at your end may vary as execution of multithreading program depends completely on processor.
You may follow following code or can get it from my GitHub repository. 

Example of Multithreading by using Thread Class:

/**
 *
 * @author YogeshD
 Title: To show use of Multi-threading by using Thread class (Extending Thread class)
 */

class One extends Thread
{
    public void run()
    {
        System.out.print("You are inside of Class One:");
        for(int i=1;i<10;i++)
        {
            System.out.println("i="+i);
        }
        System.out.println("End of Class One");
    }
}
class Two extends Thread
{
    public void run()
    {
        System.out.print("You are inside of Class Two:");
        for(int j=1;j<10;j++)
        {
            System.out.println("j="+j);
        }
        System.out.println("End of Class Two");
    }
}
class Three extends Thread
{
    public void run()
    {
        System.out.print("You are inside of Class Three:");
        for(int k=1;k<10;k++)
        {
            System.out.println("k="+k);
        }
        System.out.println("End of Class Three");
    }
}
public class Multithreading_Basics {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        //Newborn State
        One Thread_One=new One();
        Two Thread_Two=new Two();
        Three Thread_Three=new Three();
    
        //Runnable State
        Thread_One.start();
        Thread_Two.start();
        Thread_Three.start();
    }
}



A sample output is also shown as following,
Executed First time:

run:
You are inside of Class One:i=1
i=2
i=3
i=4
i=5
End of Class One
You are inside of Class Two:j=1
j=2
j=3
j=4
j=5
End of Class Two
You are inside of Class Three:k=1
k=2
k=3
k=4
k=5
End of Class Three
BUILD SUCCESSFUL (total time: 2 seconds)


Executed Second time:

run:
You are inside of Class One:You are inside of Class Two:i=1
i=2
i=3
i=4
i=5
End of Class One
j=1
j=2
j=3
j=4
j=5
End of Class Two
You are inside of Class Three:k=1
k=2
k=3
k=4
k=5
End of Class Three
BUILD SUCCESSFUL (total time: 0 seconds)


==>Posted By Yogesh B. Desai

Next Post: Multithreading in JAVA using Runnable Interface

Previous Post: JAVA Home Page


You are Visitor Number:
counter

No comments:

Post a comment