Sunday, 6 October 2013

Multithreading in Java

This is one of the very interesting topics in java. Spawning multiple thread to do the parallel tasks.Here you have to take care of resource handling,locking,unlocking otherwise application will buzzed off.

So if we talk about how thread to be implemented? .Definition of thread is the path of execution which shares its memory,resources with the process. Then java provides two ways to implement thread . one is by implementing Runnable interface and second one is by extending Thread class.

Following is the detail of thread implementation :
  • Runnable interface : 
       By implementing runnable interface you can  implement threading.Inside runnable interface you have to override run method to start the thread.
Ex.


public class Threading implements Runnable
{

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Thread t=new Thread(new Threading());
        t.start();
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("In run...");
    }
}


  • Second way is by extending thread class.Code is as below
 public class Threading extends Thread
{

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Threading t=new Threading();
        t.start();
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("In run...");
    }

}


In above two implementation you may have noted that after creating an object we are calling start method and run method gets executed and to start the thread you must have to call start method on thread instead of run.If you call run method then thread will not be created. So the point is when you call start method on thread internally it spawns new thread and executes code inside run method.

Some of the important points about threads are as below:
  • Thread can be implemented by two ways (Runnable interface and Thread class)
  • Normally it is preferred to implement Runnable interface so that you could extend another class at a time.
  • To do the resource handling you have to use synchronization.
  • Thread execution scheduling is depending upon the underlying operating system scheduling scheme.

No comments:

Post a Comment