Saturday, November 14, 2015

Multithreading in java

Introduction:

Thread:

  •  A thread is a lightweight sub process, a smallest unit of processing 
  •  It is a separate path of execution.
  •  Threads are independent, if there occurs exception in one thread, it doesn't affect other threads  
  •  It shares a common memory area.
               


  • Multithreading in java is a process of executing multiple threads simultaneously.
  • But we use multithreading than multiprocessing because threads share a common memory area.
  •  They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Use of Multithreading in java:

  • The main application area of multithreading is videogames implementation, Multimedia graphics etc...

Advantages of Multithreading in java:

  1. You can perform many operations together so it saves time.
  2. It doesn't block the user because threads are independent and you can perform multiple operations at same time
  3. Threads are independent so it doesn't affect other threads if exception occur in a single thread.

Multitasking:

Executing Several tasks simultaneously is called"multitasking"   There are 2 types of Multitasking. They are
   
 1) Process based Multitasking.
 2) Thread based Multitasking.


Process based Multi Tasking:
  • Executing several tasks simultaneously where each task is a separate independent process is called ‘Process based Multitasking’.
Ex:
  • While writing java program in the editor we can run MP3 player
  • At the same time we can download a file from the net. All these tasks are executing simultaneously and independent of each other.
  •  Hence it is process based Multitasking.
  •  Process based Multitasking is best suitable at O.S level.Process based Multi Tasking Executing several tasks simultaneously where each task is a separate independent part of the same program is called Thread based Multitasking. This type of multitasking is best suitable at programmatic level.
  • Java provides in built support for thread based multitasking by providing rich library (Thread,ThreadGroup, Runnable ..etc)
  • Whether it is Processbased or Threadbased the main objective of multitasking is to reduce response time and improve performance of the system.

We can define instantiate and starting a thread by using the following 2- ways:

 1)  By extending Thread Class.

 2) By implementing Runnable interface

1) By extending Thread Class:

 Ex:


   class MyThread extends Thread{
   public void run()
  {
   for (int i=0; i<10; i++ )
  {
   System.out.println("Child Thread");
   }
   }
  }

 class MultiThreadDemo{

 public static void main(String[] args) throws InterruptedException
{
 MyThread t = new MyThread();
 t.start();
 for(int i = 0; i<10; i++)
{System.out.println("Main Thread");
 }
 }
}
Case1 :

Thread Shedular:

  • If multiple threads are there then which thread will get chance first for execution will be decided by “Thread Scheduler”. 
  • Thread Scheduler is the post of JVM. 
  • The behavior of thread scheduler is vendor dependent and hence we can’t expect exact O/P for the above program.

The possible Outputs are:

Case2:

The difference between t.start() & t.run():

  • In the case of t.start() a new thread will be created and which is responsible for the execution of run. But in the case of t.run() no new thread will be created and run() method will be executed just like a normal method by the main thread.
  • Hence in the above program if we are replacing t.start() with t.run() then the 


OutPut is:
child
child
child
child
----
----
main
main

Case3:

Importance of Thread Class start() method:




  • After Creating thread object compulsory we should perform registration with the                      threadscheduler. 
  • This will take care by start() of Thread class, So that the programmers has   to concentrate on only job. With out executing Thread class start() method there is no chance of start a new Thread in java.

    •                                
      start(){
      Register our thread with the thread scheduler.
      Invoke run method.
        }

          Note:-

          •  we can’t stop a running Thread explicitly. But until 1.2 version we can achieve this by using stop() method but it is deprecated method. 
          • Similarly suspend() and resume() methods also deprecated.
          • After starting a thread we are not allowed to restart the same thread once again, violation leads to Runtime Error saying “IllegalThreadStateException”.

          EX :                    

          MyThread t = new MyThread();

          t.start();

          t.start(); // Illegal Thread state Exception


          By Implementing Runnable Interface:


          • We can define a Thread by implementing runnable interface also. Runnable interface available in java.lang package and contains only one method

                public void run();


          Ex:

          class MyRunnable implements Runnable{
          public void run(){
          for(int i = 0;i<=10;i++){
          System.out.println("Child Thread");
          }
          }
          }
          class ThreadDemo{
          public static void main(String arg[]){
          MyRunnable r = new MyRunnable();
          Thread t = new Thread(r);
          t.start();
          for(int i = 0;i<=10;i++){
          System.out.println("Main Thread");
          }
          }
          }

          Possible Output is:
                                               

          Ex:

          MyRunnable r = new MyRunnable();
          Thread t1 = new Thread();
          Thread t2 = new Thread(r);


          Case1:

          t1.start();
          • A new thread will be started and executes thread class run method(Which is having empty implementation).
          Case2:

          t1.run();

          • No new thread will be created and thread class run() method will be executed just like a normal method call.
          Case3:

          t2.start();
          • A new thread will be created and responsible for execution of MyRunnable run method.
          Case4:
          t2.run();
          • No new thread will be created and MyRunnable run method will be executed just like a normal method call.
          Case5:
          r.run();
          • No new thread will be created and MyRunnable run method will be executed just like a normal method call.
          Case6:
          r.start();
          • Compiler Error: MyRunnable doesn’t contain start method.

           Also Read this post: Life Cycle of Thread in java 

          No comments:

          Post a Comment

          High Paying Jobs after Learning Python

          Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...