Monday 12 May 2014

Creating Threads in JAVA

Introduction to multithreading

Thread Creation

We can Create threads in Java by using the following two ways.
  1. By Extending Java.lang.Thread class.
  2. By implementing the Java.lang.Runnable interface.
  1. Create thread by extending Thread class
  • The class should extend Java Thread class.
  • The class should override the run() method.
  • The functionality that is expected by the Thread to be executed is written in the run() method.
Example:

class MyThread  Extends  Thread{
          Public Void run(){
     system.out.println("thread started running.....");
                                   }
}


class MyThreadDemo{
       
             Public Static void main(String srgs[]){
                            MyThread obj=new MyThread();
                               obj.start();
                           }
}


2.Create Thread by implementing Runnable interface



    • Other way of creating a thread is to create a class that implements the Runnable interface. We must need to give the definition of run() method.This run method is the entry point for the thread and thread will be alive till run method finishes its execution.
    • Once the thread is created it will start running when start() method gets called. Basicallystart() method calls run() method implicitly.

      Example:

      class MyThread  implements Runnable{
                Public Void run(){
           system.out.println("thread started running.....");
                                         }
      }

      class MyThreadDemo{
           
                   Public Static void main(String srgs[]){
                                  MyThread obj=new MyThread();
                                    Thread t1=new Thread(obj);
                                     t1.start();
                                 }
      }

      Multi-threading in Java


      Thread??

      • Multi-tasking allows multiple programs to be run at the "same" time. Lets visualize this as  each application as running on its own processor.

                        






      • Just like programs can run concurrently, pieces of the same program can run concurrently. This ability is known as Threading.
      Example:

      •  Lets consider a very simple example.Lets assume that we have an array of 10000 like

                              Array a[10000];

      •  Here our task is to add all the array element values.so generally we use some thing like
                          for(i=0;i<10000;i++){
                                  sum=sum+sum[i];
                                 }
      •  So by adding all the 10000 values by single process(or like by one person) it will take lot of time to do this.
      • Instead of doing this as a single program ,Lets divide this tasks among 10 persons as 10 pieces of tasks(threads)like
                          person1  =add a[1]      to a[1000]--->thread 1
                          person2  =add a[1001] to  a[2000]--->thread2
                           .........
                          person10=add a[9001]  toa[10000]-->thread 10
      • Lets allow all these 10 multiple  threads run concurrently.So we will save time and work load of single program by performing multithreading.

      Multithreading in java

      Java multithreading allows you to do multiple tasks at the same time.
      • Every java program creates at least one thread [ main() thread ]. we can create additional threads whenever needed.
      • In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution running concurrently. It allows a program to be more responsible to the user. When a program contains multiple threads then the CPU can switch between the two threads to execute them at the same time.
      • Threads are lightweight processes; they share the same address space. In Multithreaded environment, programs make maximum use of CPU so that the idle time can be kept to minimum.
      • There are several thread states, A thread can be in any one of the state at a particular point of time. It can be running state. It can be ready to run state as soon as it gets CPU time. A running thread can be suspended. A suspended thread can be resumed. A thread can be blocked when waiting for a resource. At any time a thread can be terminated.

      Whats the need of a thread or why we use Threads?

      • To perform asynchronous or background processing
      • Increases the responsiveness of GUI applications
      • Take advantage of multiprocessor systems
      • Simplify program logic when there are multiple independent entities


      What happens when a thread is invoked?


      When a thread is invoked, there will be two paths of execution. One path will execute the thread and the other path will follow the statement after the thread invocation. There will be a separate stack and memory space for each thread.


      Thread Lifecycle



      1. New state : After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.
         
      2. Runnable (Ready-to-run) state A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. 
      3. Timed waiting is a thread state for a thread waiting with a specified waiting time. 
      4. waiting state due to the calling one of the following methods without     timeout:Object.wait() or Thread.join()
      5. blocked : A thread can enter in this state because of waiting the resources that are hold by another thread.
      6. After thread has completed execution of run() method, it is moved into terminated /Dead state . If any thread comes on this state that means it cannot ever run again.
      Note, that thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object. A thread that has called Thread.join() is waiting for a specified thread to terminate. It means that waiting state could be made a composite state with states corresponding to these specific conditions.
      Methods to Manage Threads:
      • getName()     :This is used to obtaining Thread's Name.
      • setName()      :To give thread a name.
      • getPriority()    :Obtains a thread Priority.
      • isAlive()         :Determine If the thread is still running.
      • join()             :Wait for a thread to terminate.
      • run()              :Entry point for the thread.
      • sleep()           :suspend a thread for a period of time.
      • start()            :Start a thread by calling its run() method.
      • notify()           :This wakes up threads that called wait() on the              same object and moves the thread to ready state.
      • notifyAll()     :This wakes up all the threads that called wait() on the same object.
      • Yield()            :It is used to give the other threads of the same Priority a chance to execute i.e.causes current running thread to move to reunnable State.
      • Stop()        :The stop() method is used to stop the execution of a thread before its run() method terminates.

      To know how to create threads..please click here.