Java Threads

SINGLE TASKING:

        Executing one task at a time is called Single Tasking. Processor executes only one program at a time. The remaining programs should wait until the first program completes. So, here in this single tasking, much amount of time is wasted.



Fig: Single Tasking

MULTI TASKING: 

         Suppose let us take our PC. In that we can play songs, create documents, watch videos etc... all these three can be done at once, This is called Multi Tasking. i.e., Executing more than one program(process) at a time is called Multi Tasking. The main advantage of multi tasking is to utilize the processor time in the better way. By this performance can be achieved. 

There are two types of Multi Tasking: they are: 
  1. Process Based Multi Tasking (Running more than one program at a time)
  2. Thread Based Multi Tasking(Several parts of a program are executed at once)
Now let us know what is a thread:

THREAD: A Thread is a part of a program that performs some task. 

'Thread' CLASS:  

This class is present in java.lang package. This class consists of the methods that are to be implemented in the thread. We can see the method of the Thread class by using javap command in the command prompt. To create a thread we should extend the Thread class.
use of Javap command
Fig: Thread class in java.lang package

'Thread' class Methods:  

The following are the methods of Thread class.
  • currentThread() : To know the currently executing thread.
                             Eg: Thread t = Thread.currentThread();
  • start()                 : To start thread execution.
                             Eg: t.start(); 
  • sleep()               : To stop execution of a thread for a specified period of time.
                            Eg: Thread.sleep(milliseconds); 
  • getName()         : To get the name of the Thread.
                            Eg: String name = t.getName(); 
  • setName()         : To set the name of the Thread.
                            Eg: t.setName("new name") ;
  • getPriority()       : To get the Thread priority. 
                           Eg: int p = t.getPriority(); 
  • setPriority()       : To set the Thread priority.
                           Eg: t.setPriority(int num) ;
  • isAlive()             : To test if a Thread is still alive. This returns true/false.
                           Eg: t.isAlive() 
  • join()                   : To wait till the Thread dies. 
                           Eg: t.join()
       Thread Priority can change from 1to 10. The default priority of the Thread is 5.  We can also use the following constants to represent priorities: 
  • Thread.MAX_PRIORITY       (10)
  • Thread.MIN_PRIORITY         (1 )
  • Thread.NORM_PRIORITY    ( 5) 

 'Runnable' INTERFACE:

 This also present in java.lang package. This interface consists of an abstract method, that is used to run a thread.
Runnable Interface
Fig: Runnable interface in java.lang package.

Creating a Thread: 

  The following are the steps to create a Thread.
Step 1: Create a class that extends Thread class or implements unnable interface. 

 Eg: class MyThread extends Thread {
          .........................
           }
                                     or

         class MyThread implements Runnable{
            .........................
          }

Step 2: Write the functionality of the thread inside the run() method. 

  Eg: public void run(){
          .........stmts.........
          } 

Step 3: Create an object to MyThread.

  Eg: MyThread mt = new MyThread();

Step 4: Attach MyThread object to the Thread class object.

Eg: Thread t = new Thread(mt);

Step 5: Start the execution of the thread.

Eg: t.start(); 

          When we create a user Thread by extending a Thread class then we don't have a chance to extend from any other class.When we create a user Thread by implementing a Runnable Interface, then we have a chance to extend from any one class. So, it is recommended to create a thread by using Runnable interface

The following figure shows the example program for Multiple threads:
Multithread Program
Fig: Multi thread program

Result for Multi Thread program.
Fig: Result for Multi Thread program.

Multiple Threads Acting on a Single object:        

           In java programs we will assign an object to each task. Here two different threads want to perform the same task, i.e., they both want to act upon a single object. The following example explains you clearly.
          Suppose let us think that two persons move to bus reservation counters at two different places. Both of them wants to book the ticket to the same bus and same destination. Let us think that only one seat is available. In reservation conter.1 the person1 sent a request to the server to allot that seat. In counter.2 ,person 2 also sent a request to the server to allot that seat. Now let us see to whom the seat is allotted. 
Multiple threads acting upon a single object
Fig: Multiple Threads acting upon same object.

Multiple threads acting upon a single object
Fig: Result for Multiple Threads acting upon same object.

        In the above result we can see that 1 sea is allotted to two persons., which is not possible. The solution for this problem is THREAD SYNCHRONIZATION, or THREAD SAFE. 
What is this Thread Synchronization? let us see....

Thread Synchronization:

         When a Thread is acting upon an object, preventing the other Thread from acting upon the same object is called Thread Synchronization, or Thread Safe. The object on which the Threads are synchronized is called Synchronized object
Thread Syncronization
Fig: Thread Synchronization
we can synchronize the object in two ways as follows:
  • Using synchronized block: we can place all the statements of run() within this block as shown below.
synchronized(object)
{
     ,,, statements ,,,
}

  • Using synchronized keyword: we can synchronize the entire method using synchronized keyword. suppose, if we want to synchronize the code of display() method, we can do as follows.
synchronized void display()
{
    ,,, statements ,,,
}

Now try the ticket reservation program using synchronization. Just keep do as follows:
class Reservation implements Runnable {
     //statements
        public void run() {
              synchronized(this)  {
                   // statements.....
              }
        }
class MultiThread {
    // statements
}

Deadlock: 

         When two threads or processes are waiting for each other to release the resource or object they holds and so are blocked forever. This situation is called deadlock. For example if one thread is holding the lock on some object that the other thread is waiting for and the other thread is holding lock on some object the first one is waiting for then they both will wait for each other to release the object they need to finish their operation but no one will release the hold object and so they will wait for each other forever. The following figure shows the deadlock. 
Thread Deadlock
Fig: Deadlock in Threads.

The only solution for deadlock is to write the program carefully without occuring deadlock.  

Thread Communication: 

         Some times we need the threads to communicate with each other. Suppose if a thread t1 is executing a task and t2 is executing another. If t1 wants the result of t2 for its further execution it should wait until the t2 completes execution and at the same time t2 should notify t1 about the completion of its execution. The following methods helps us in establishing the Thread communication. These methods are available in'java.lang.object'.
  • wait(): This method is used to make a Thread wait until it get a notification.
  • notify(): This method gives the notification to one of the waiting Threads.
  • notifyAll(): This method will send a notification for all the waiting Threads.

No comments:

Post a Comment