Friday, August 31, 2012

Thread Concept Part-II


Thread State

Every thread has five states. Those are start, runnable, running, waiting or suspend and dead.

                  i.   A thread comes from start state to runnable state before enter into the running state.

                ii.   start() method start the thread. In this method execution thread comes in runnable state first and enters into running state. The JVM manages the state transition of thread.

               iii.   According to the processor execution time allotment the thread goes to wait or suspend state.

              iv.   When wait(), sleep() and join() methods are invoked then running thread shifts into suspend or waiting state.

                v.   In case of yield() method invocation the thread directly enter into runnable state from running state.

              vi.   The thread comes again runnable state before enter into running state.

             vii.   In all above states thread is alive.

           viii.   After completing the thread execution, thread enters into dead state. In dead state thread is not alive.


 

Thread Synchronization

Synchronization is the technique to share an object one-by-one by multiple threads. In other way, allow only single thread to access an object at a time. Prevent an object from concurrent access of multiple threads is called Thread-Safe.

How to synchronize?

There are two ways to synchronize the code. Those are synchronized keyword and synchronized block.

1.       synchronize keyword

 
Use synchronized keyword in method definition for synchronize access.


public class DomainClass {

     public synchronized void methodName() {

           // Code here

     }

}

Points need to remember –

                                                      i.      synchronized keyword prevent only method from concurrent access by threads.

                                                    ii.      synchronized is used for method only not for class or properties.

                                                   iii.      synchronized method locks the same object at the time of execution.

                                                  iv.      One class can contain synchronized and non-synchronized methods.

                                                    v.      If multiple threads are using different instance of an objects then threads accurse lock of their object instance.

                                                  vi.      Thread can get multiple if any synchronization code invokes any other synchronized method.

 

2.        synchronize block

 
synchronized blocks is used to synchronized a block of code in the method. synchronized keyword locks only one object i.e. the same object. In synchronized block has to provide the locking object. It provides the flexibility to lock particular object. It also provides lock over multiple objects.


public class DomainClass {

public void methodName () {

           synchronized (this) {

                 // Code here

           }

}

}

 

Points need to remember –

                                                      i.      Synchronized set of code in a method.

                                                    ii.      synchronized block provides multi object locking functionality.

                                                   iii.      Provide locking object instance for synchronized block.

                                                  iv.      ‘this’ locking object indicates to lock the same object.

 

Object Locking

Object is locked by thread when executes synchronized code. When thread executes synchronized code then it locks locking object to each other. After executing synchronized code it releases the lock.

 


 

Thread Example#2

This example for wait() and notify() with synchronize method function using three threads.

§  Create a domain class with synchronized block (file name: WNDomainClass.java)

public class WNDomainClass {

   private int wnPropItem;

   private boolean flag = false;

 

   public synchronized void setWNPropItem(int wnPropItem) {

         if (!flag) {

               try {

                     wait();

               } catch (Exception e) {}

         }

         System.out.println(Thread.currentThread().getName() + " : "

                     + this.getClass().getName()

                     + "().setWNPropItem(int wnPropItem): ["

+ wnPropItem + "]");

         this.wnPropItem = wnPropItem;

         flag = false;

         notify();

   }

 

   public int getWNPropItem() {

         synchronized (this) {

               if (flag) {

                     try {

                           wait();

                     } catch (Exception e) {}

               }

               System.out.println(Thread.currentThread().getName() + " : "

                           + this.getClass().getName()

+ "().getWNPropItem(): ["+ wnPropItem + "]");

               flag = true;

               notify();

         }

         return this.wnPropItem;

   }

}

 

§  Create thread class implemanting java.lang.Runnable interface. (file name: WNMyThreadClass1.java)

public class WNMyThreadClass1 implements Runnable{

   private WNDomainClass wnDomainClass;

  

   public WNMyThreadClass1(WNDomainClass wnDomainClass){

         this.wnDomainClass=wnDomainClass;

   }

  

   @Override

   public void run() {

         System.out.println(Thread.currentThread().getName() +" START ");

        

         WNMyThreadClass2 wnMTC2=new WNMyThreadClass2(wnDomainClass);

         Thread t2=new Thread(wnMTC2);

         try{

               t2.join();

         }catch (Exception e) {}

        

         for(int i=0; i<5 i="i" span="span">

               wnDomainClass.setWNPropItem(i);

               try{

                     Thread.sleep(1000);

               }catch (Exception e) {}

         }

         System.out.println(Thread.currentThread().getName() +" STOP ");

   }

}

 

§  Create another thread class implemanting java.lang.Runnable interface. (file name: WNMyThreadClass2.java)

public class WNMyThreadClass2 implements Runnable{

 

private WNDomainClass wnDomainClass;

  

   public WNMyThreadClass2(WNDomainClass wnDomainClass){

         this.wnDomainClass=wnDomainClass;

   }

  

   @Override

   public void run() {

         System.out.println(Thread.currentThread().getName() +" START ");

         for(int i=0; i<5 i="i" span="span">

               wnDomainClass.getWNPropItem();

               try{

                     Thread.sleep(1000);

               }catch (Exception e) {

               }

         }

         System.out.println(Thread.currentThread().getName() +" STOP ");

   }

}

 

§  Create Main method class (file name: WNMyThreadMain.java)

public class WNMyThreadMain {

   public static void main(String[] args) {

 

         WNDomainClass wnDomainClass=new WNDomainClass();

        

         WNMyThreadClass1 wnMTC1=new WNMyThreadClass1(wnDomainClass);

         WNMyThreadClass2 wnMTC2=new WNMyThreadClass2(wnDomainClass);

        

         Thread t1=new Thread(wnMTC1);

         Thread t2=new Thread(wnMTC2);

        

         t1.start();

         t2.start();

   }

 

}

 

§  Run and see output

Thread-0 START

Thread-1 START

Thread-1 : pack.thread.WNDomainClass().getWNPropItem(): [0]

Thread-0 : pack.thread.WNDomainClass().setWNPropItem(int wnPropItem): [0]

Thread-1 : pack.thread.WNDomainClass().getWNPropItem(): [0]

Thread-0 : pack.thread.WNDomainClass().setWNPropItem(int wnPropItem): [1]

Thread-1 : pack.thread.WNDomainClass().getWNPropItem(): [1]

Thread-0 : pack.thread.WNDomainClass().setWNPropItem(int wnPropItem): [2]

Thread-1 : pack.thread.WNDomainClass().getWNPropItem(): [2]

Thread-0 : pack.thread.WNDomainClass().setWNPropItem(int wnPropItem): [3]

Thread-1 : pack.thread.WNDomainClass().getWNPropItem(): [3]

Thread-0 : pack.thread.WNDomainClass().setWNPropItem(int wnPropItem): [4]

Thread-0 STOP

Thread-1 STOP

 

Thread Concept Part-I


Thread

All java programs are run under a thread in JVM. Java program runs in default thread called “main” thread.  Java main method is invoked the JVM start ‘main’ thread to run the program. Java has capability to run multiple threads for application. But multi-threading is the most unpredicted behavior for any java application at runtime.

Every thread is run in different stack in JVM. Multi-threading is talking about to run multiple thread at a time to perform multiple operations. System processor schedules the time frame to run the thread one by one. All threads are come in a queue use processor time to execute.

There several procedure to prioritize the threads in queue. Mainly “Round-Robin” theory is applied for allocating process time. Set priority is another procedure to schedule the queue for processor execution sequence. But there is no guaranty thread will be executed with applied theories and schedule. Thread execution behavior will be different for different systems, different operating systems and different infrastructure.

Thread Creation

There are two ways to create thread in java. Java provides ‘Runnable’ interface and ‘Thread’ class for thread programming.

1.       Extends ‘Thread’ class.

a.       Extends java.lang.Thread class in your thread class

b.     
 
Override run() method for operation.


public class FirstMyThread1 extends Thread{

   public void run() {

                  System.out.println(" New thread started. :"

                     + Thread.currentThread().getName());

         System.out.println(" Add operation code here for new thread.");

   }

}

2.       Implements ‘Runnable’ interface

a.       Implement java.lang.Runnable interface in your class.

b.     
 
Implements run() method for operation.


public class FirstMyThread2 implements Runnable{

   @Override

   public void run() {

                  System.out.println(" New thread started. :"

                     + Thread.currentThread().getName());

         System.out.println(" Add operation code here for new thread.");

   }

}

 

 

 

Thread Start

Create Thread class object and call the start() method to run the new thread.

1.       Extends ‘Thread’ class.

MyThread1 mThread1=new MyThread1();

mThread1.start();

 

2.       Implements ‘Runnable’ interface

MyThread2 mThread2=new MyThread2();         

Thread t1=new Thread(mThread2);

t1.start();

 

Points need to remember –

i)        start() method is in jav.lang.Thread class

ii)       As your thread class extends java.lang.Thread class then you can call start() method directly.

iii)     You implements java.lang.Runnable interface to create my thread class

a.       You only override run() method

b.      start() method is not available in your thread class.

c.       So pass your thread class in java.lang.Thread class to assign thread task.

d.      In this case your thread class only define thread job

e.      Here java.lang.Thread class is a worker class to execute you job

iv)     mThread1.run() or mThread2.run() are valid method call

a.       If you call mThread1.run() then new thread will not start.

b.      This method will execute as part of current thread.

c.       No exception will thrown

v)      If you start more than one thread there is no guaranty to start those threads in your order you started.

vi)     All thread will be started from main thread.

 


 

Thread Example#1

§  Create thread class extending java.lang.Thread class (file name: FirstMyThread1.java)

public class FirstMyThread1 extends Thread {

   public void run() {

         System.out.println(" New thread started. :"

                     + Thread.currentThread().getName());

         System.out.println(" Add operation code here for new thread.");

   }

}

§  Create thread class implementing java.lang.Runnable interface (file name: FirstMyThread2.java)

public class FirstMyThread2 implements Runnable {

   @Override

   public void run() {

         System.out.println(" New thread started. :"

                     + Thread.currentThread().getName());

         System.out.println(" Add operation code here for new thread.");

   }

 

}

§  Create Main method class (file name: FirstMyThreadMain.java)

public class FirstMyThreadMain {

   public static void main(String[] args) {

         FirstMyThread1 fmThread1=new FirstMyThread1();

         fmThread1.start();

        

         FirstMyThread2 fmThread2=new FirstMyThread2();

         Thread t=new Thread(fmThread2);

         t.start();

   }

}

§  Run and see output

New thread started. :Thread-0

New thread started. :Thread-1

Add operation code here for new thread.

Add operation code here for new thread.