Wednesday, 24 August 2016

Multi Threading Introduction

Multi Threading

A thread is a light-weight smallest process that can run concurrently with the other threads of the same process and has its own call stack. Threads are independent because they all have separate path of execution that’s the reason if an exception occurs in one thread, it doesn’t affect the execution of other threads. All threads of a process share the common memory. The process of executing multiple threads simultaneously is known as multithreading.
In Java there is one thread per call Stack , Even if we don’t create threads in our program, threads are running in background.

Since we know that the whole execution starts from main() method, so that main() method run in one thread known as main thread, If we look main call stack trace, we can see that main() is the first method on the stack , but as soon as we create a new thread , a new stack created and method called from that thread run in a call stack that is different from main() call stack.

A very nice quote about thread :

When it comes to threads  , a very little is guaranteed
                                                                                    --- Kathy Sierra

Difference between Multitasking – Multithreading  - Multiprocessing - Parallel Processing.

I have seen people are often confused between below mentioned terms.

Multitasking: Ability to execute more than one task at the same time is known as multitasking.
Multithreading: We already discussed about it. It is a process of executing multiple threads simultaneously. Multithreading is also known as Thread-based Multitasking.
Multiprocessing: It is same as multitasking, however in multiprocessing more than one CPUs are involved. On the other hand one CPU is involved in multitasking.
Parallel Processing: It refers to the utilization of multiple CPUs in a single computer system.
Creation of a Thread
A thread in java begins as an instance of java.lang.Thread. Lets have a look at these methods of Thread class.
  • start() – Start a thread by calling its run method.
  • run() – Entry point of thread i.e the action happens in the run() methods, you always write the code that needs to be run in a separate thread in a run() method. The run method will call other methods
  • getName(): It is used for Obtaining a thread’s name
  • SetName(): It is used set a thread’s name.
  •  getPriority(): Obtain a thread’s priority.
  •   isAlive(): Determine if a thread is still running
  •   join(): One Thread join into the end of another thread and it will wait for a current dependent thread to terminate
  • Sleep(): suspend a thread for a period of time
  •  Yield() : Cause a thread to go from  running to runnable
  • getId(): This Method return a positive, unique, long number and that number will be thread’s only number for the thread’s entire life.



There are two ways to create a thread in java
Ø Extending Thread class
Ø Implementing Runnable Interface
Please Note: Every thread of execution begins as an instance of Thread class.
Regardless of whether you run() method in a Thread subclass or a Runnable implementation class
n  A new thread of execution starts(with a new call stack)
n  The thread moves from the new state to the runnable state.
n  When a thread gets a chance to execute , it targets run() menthod

Example : - Extending Thread class
Example 1 :
package multithreadingtc;
/**
 *
 * @author shashank
 */
public class MultithreadingTC extends Thread{

    public void run()
    {
        System.out.println("Execution starts here");
    }
    public static void main(String[] args) {
        // TODO code application logic here
        MultithreadingTC th = new MultithreadingTC();
        th.start();
}
}



Example 2 :
package multithreadingtc;
/**
 *
 * @author shashank
 */
class Multithreading extends Thread
{
   public void run()
    {
        System.out.println("Execution starts here");
    }
}
public class MultithreadingTC{

    public static void main(String[] args) {
        // TODO code application logic here
        Multithreading th = new Multithreading();
        th.start();
    }
   
}
Example implementing Runnable Interface
Example 1:
package multithreadingrunnable;
/**
 *
 * @author shashank
 */
class Multithreading implements Runnable
{
     public void run()
    {
        System.out.println("Execution starts here");
    }
}
public class MultithreadingTC{
    public static void main(String[] args) {
        Multithreading th = new Multithreading();// Instantiate Runnable class
        Thread t = new Thread(th);// Pass your runnable instance to the Thread
        t.start();
    }
}
Example : Running multiple threads
package multithreadingtc;

/**
 *
 * @author shashank
 */

class Multithreading implements Runnable
{
     public void run()
    {
        for(int i=1;i<=3;i++)
        {
            System.out.println("run by" + Thread.currentThread().getName() + " value of i is " +i);
        }
    }
}
public class MultithreadingTC{

    public static void main(String[] args) {
        // TODO code application logic here
        Multithreading th = new Multithreading();
        Thread t = new Thread(th);
        t.setName(" first");
        t.start();
        Thread t1 = new Thread(th);
        t1.setName(" second");
        t1.start();
        Thread t2 = new Thread(th);
        t2.setName(" third");
        t2.start();
    }
   


}

Please follow my next article over Thread States/Transitions/Scheduling and Synchronization.

No comments:

Post a Comment