Tuesday, 23 August 2016

Multithreading in java

By,
Santosh

Multithreading is a process of executing (running) multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of process. Multiprocessing and multithreading are used to achieve multitasking.
We use multithreading than multiprocessing because threads share a common memory area. context-switching within the threads takes less time than process.
Java Multithreading is mostly used in application, games, animation etc.

Advantage of Multithreading :-
1) It doesn't block the user because threads are independent and we can perform multiple tasks at       
    same time.
2) we can perform many tasks together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread
    is stop working.

Multithreading
Multithreading is a process of executing (running) multiple tasks at the same time (simultaneously). You use Multithreading to utilize the CPU. Multithreading can be achieved by two ways.
• Process-based.
• Thread-based.

1) Process-based -
• Each and every process has own address in memory i.e. each process allocates separate
   memory address.
• Process is heavyweight.
• communication within the process is high.
• Switching from one process to another require some time.

2) Thread-based -
• Share the same memory space.
• Lightweight.
• Communication within the thread is low.

Thread in java -
A thread is a lightweight so it does not require separate memory area.
A small unit of processing.
It is executed separately from other thread, it does not affected other thread when one is stop because of exception.
Thread is run independently,
Thread shares a common memory area within the application.

How to create Thread
Example :-
1) Creating thread by using Thread Class

class MultiThread extends Thread

    void run()
    {
        System.out.println("your first Thread is running Now "); 
    } 
    public static void main(String []args)
    { 
        // Creating the object of test class
        MultiThread  obj1=new MultiThread  ();
        obj1.start();  
    }
}


2) Creating thread by using Runnable interface

class MultiThread2 implements Runnable
{
     public void run()
    { 
        System.out.println("Thread is created using Runnable Interface ..."); 
    } 
     public static void main(String []args)
    {
        // class object creation 
        MultiThread2  obj2=new MultiThread2 (); 
        //Passing class object to Thread class
        Thread t1 =new Thread(obj2);
        t1.start();
     }