Header Ads

Multithreaded Programming

 



What is Multithreading?

It is conceptual programming in which a program (process) is divided into two or more subprograms, which can be implemented at the same time in parallel.

1. Multithreaded means two or more parts of program can run concurrently i.e. at the same time you can run two or more parts (or method) of the program.
2. Each part of that program called Thread.
3. Each thread defined a separate path of execution
4. Multithreading enables you to write very efficient program. Using multithreading we can maximize the use of CPU. Multithreading is part of Multitasking in Operating system.
5. Multitasking comes in two flavor 1) Process based and 2) Thread based.
6. Process based means separate program and Thread means part of the program
7. For example If you are running MSWORD and MSEXCEL at the same time means you are running the two process concurrently.
8. If you are running only MSWORD and you are typing as well as Spell CHECK running in background i.e. different thread in one process.
9. Thread lightweight version of Process. Process is heavyweight

Example: One program can read input from the user while other can print the characters as read. It is similar to divide the work and assigning it to separate persons who can work on it simultaneously.

Difference between Multithreading and Multitasking

difference between multithreading and multitasking

ADVANTAGES OF MULTITHREADING

Faster Execution Time:

Since separate threads can  perform independent tasks, Multithreading can speed up execution time.
Ex. If there is a program where you need to read input from the user and operate on data as it comes. If you operate on parts of data it may happen that the user may not input data for a long time. In a normal program you would have to wait for it until user enters the data. However, in multithreaded programs while the user is idle, you can take the part of data entered by user already and work on it.

PROBLEMS IN MULTITHREADING:

1. Data can be corrupted in a multithreaded environment: If more than one thread manipulates shared variables or objects at the same time, corruption may result. Instance variables are shared between threads. If one is modified by a thread, the change affects the other threads.

2. Possibility Deadlock: This can occur due to circular dependency of one thread waiting for resource occupied by another and another waiting for the resource occupied by the first one.

HOW TO CREATE THREADS

There are two ways to create thread:

1) We can create thread by extends the Thread class
2) We can create thread by implement the Runnable interface.

FIRST APPROACH

Steps to create Thread by extending Thread class

1)  Create any class and extend Thread in it.          
2). Create instance(Object) of that class
3)  Extending class should override run() method
4)  Call start() to begin execution of new Thread.

Syntax:

class NameOfChildThreadClass extends Thread
{
    public void run( )
    {
        //code associated with child thread class
    }
}

SECOND APPROACH

Steps to create Thread by implements runnable

1)  A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.
2)  An object of Thread class created by passing a Runnable object as argument to the Thread constructor. The Thread object now has Runnable object that implements the run() method.
3The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.

Syntax:

class NameOfChildThreadClass implements Runnable
{
     public void run()
     {
          //code associated with child thread class My thread
      }
}

THREAD LIFE CYCLE 

thread life cycle

Thread Life Cycle or Thread Transitions:

1.  Life cycle of thread can be expressed as different thread states.
2.  Different thread states can be as follows
     1) Newborn state 2) Runnable state 3) Running state 4) Blocked State 5) Dead state.
3.  A thread is always in one of these five states. It can switch from one state to other state
4.  As shown in figure during the life cycle of thread, thread is always in one of the state from five states
5.  New Born State: The moment you create the thread we can say thread is born and we can say thread state is newborn state
6.  After thread is born we can block the thread or stop thread by using standard thread method from Thread class.
7.  Runnable State The runnable thread means that the thread is ready for execution and its waiting for availability of the processor. That means thread is in the queue.
8.  Thread follows the priority higher priority thread will run first then lower.
9.  In some situation the same or equal priority thread run in round robin fashion. However if we want to relinquish control to other thread to equal priority before its turn, we can use yield () method.
10.  Running state means simply thread is running and utilizing the processor.
11.  Running thread can be suspended by suspend() methods and can be resume by resume() method.
12.  Running thread we can put to sleep means for the specified time period we can put thread to sleep means out of queue for specified the time period inside sleep(time in milliseconds) method, Once the time period is elapsed the thread re enter in runnable state.
13. We can say to thread to wait till some event occur event occur by wait() method and same thread can resume  its operation by notify() method.
14. Blocked state means thread prevented from entering into runnable state. It can achieve by using suspend() method.
15. Dead State: Just like human being every born thread has to die thread life get over when run(method get over It is the natural death of thread. However we can kill it by using stop method thus causing the premature death to it. Thread can be killed at any state for example as soon as thread born, or when thread is running, or even when thread is not runnable state.

CONSTRUCTOR OF THREAD CLASS

default constructor: When the objects of thread class are created then default constructor are implicitly executed and names of threads are automatically generated starting with Thread-0,Thread-1,Thread-2,...,Thread-n. Consider following example
   
              Thread t1 new Thread();   // name of t1 is Thread-
              Thread t2 new Thread();   // name of t2 is Thread-
              Thread t3 new Thread();   // name of t3 is Thread-2

Parameterized Constructor (String as parameter): When object of Thread class takes string as parameter, Parameterized constructor is implicitly executed and string name becomes the new name of the thread. Consider following example

      Thread t1 new Thread ("java thread"); // name of t1 is java thread

THREAD METHODS

Java's Entire multithreading system builds upon Thread class. Thread class defines several method to manage Thread operations. Few of them like as follows 

thread methods

THREAD EXCEPTIONS

1. While doing multithreaded program in java java provided effective way to handle the errors and exception.
2. Java uses its standard mechanism to deals with exception and error is try-catch block
3. Java throw IllegalThreadStateException whenever we try to invoke a method that thread cannot handle in given state for example sleeping thread cannot deal with resume() method because sleeping thread cannot receive any instructions
4. Whenever we like to thow an exception in thread we have to supply appropriate exception handler to catch it
5. Following is few forms of catch

try
{
      // Statements which need to monitored for Exception
}
catch (ThreadDeath e)
{
       ………………;    //Killer Thread
}
catch (InterruptedException e)
{
        ………………;    //Cannot handle it in the current state
}
catch (IllegalArgumentException e)
{
         ………………;    //Illegal method argument
}
catch (Exception e)
{
         ………………;    // any other exception deal with thread
}

THREAD READ PRIORITY

1. In multithread programming we have to decide thread scheduling i.e which thread run first then for how much time and which thread should wait and which thread should be suspend and for how much time.
2. All thread scheduling can be done with thread priority in java
3. If priority is same then java runtime environment will decide which thread run
4. Thread priority ranges from 1 to 10 and default priority is NORM_PRIORITY.
5. 1 MIN PRIORITY
6. 5 NORM PRIORITY
7. 10 MAX PRIORITY

SYNCHRONIZATION IN THREAD

When two or more threads need to access to a common resource, then these threads need some way to ensure that the resource will be used by only one thread at a time. The process of ensuring one access at a time by one thread is called synchronization. The synchronization is the concept which is based on monitor. Monitor is used as mutually exclusive lock. A thread that needs regular and frequent access to the common resource must acquire the lock first and then it is eligible to use the common resource. When one thread is using the common resource other threads remains in the waiting state until the thread finishes its execution.

In java every object has implicit monitor associated with it. For entering in object's monitor, the method is associated with a keyword synchronized. When a particular method is in synchronized state then all other threads have to be there in waiting state.

There are two ways to achieve the synchronization-
      
       1. Using Synchronized Blocks (Statements
       2. Using Synchronized Methods

Note: synchronization is a keyword (access modifier in java)

Synchronized block

Whenever we want to execute one or more than one statement by a single thread at a time(not allowing other thread until thread one execution is completed) than those statement should be placed in side synchronized block.

class Class_Name implement Runnable or extends Thread
{
     public void run()
     {
         synchronized(this)
         {
             …………………
             ………………….
          }
       }
  }

Synchronized method

Whenever we want to allow only one thread at a time among multiple thread for execution of a method than that should be declared as synchronized method.

class Class_Name implement Runnable or extends Thread
{
    public void run()
    {
        synchronized void fun()
        {
            ………………….
      ………………….
   }
   public void run()
   {
             fun();
              ……………………
         }     
    }
}

Program

Code

class MyThread extends Thread 
{ 		
    String message [] = {"I","Love ","Java ","Very ","Much"};  
    public void run() 
    { 
      displayList(); 
    } 

    public static synchronized void displayList() 
    {
      for (int i=0;i<message. Length();i++ ) 
      { 
         System.out.println("\n" +Thread.currentThread().getName() + message[i]); 
         try 
         { 
            Thread.sleep(2000); 
         } 
         catch (InterruptedException e) {   } 
       } 
   } 
} 
public class ThreadSync 
{ 
   public static void main(String args[]) 
   {  
       MyThread thread1 = new MyThread(); 
       MyThread thread2 = new MyThread(); 
       thread 1.setName("Thread 1: "); 
       thread2.setName("Thread 2: ");
       thread 1.start(); 
       thread2.start(); 
    }
}
Output:

Thread1 : I
Thread1 : Love
Thread1 : Java
Thread1 : Very
Thread1 : Much

Thread2 : I
Thread2 : Love
Thread2 : Java

No comments

Powered by Blogger.