Tuesday, 8 November 2016

Multi Threading in Java

Thread is lightweight, faster way to achieve multitasking.
Thread is a separate path of execution.
Threads shares common memory area and saves memory used hence they are  faster.

Thread is a part of process.It is executed inside the process.There is context switching among threads.
So OS has multiple processes and  each process has multiple threads.


Multithreading is a process of  executing multiple threads simultaneously.
Advantages -
1.It does not block user because each thread is independent.
2.It helps to do multiple operations together.

Thread Life Cycle -
There are 4 states-
1.New
2.Runnable
   Running (Optional)
3.Non-Runnable
4.Terminated 

 
 New -State when instance of thread Class is created but start() is not invoked.
 Runnable - State after start() invoked but Thread scheduler has not picked it for running.
 Running - State when Thread scheduler picked it for running.
 Non-Runnable - State when Thread is alive but not running.(Maybe blocked)
 Terminated - State when Thread is dead bacause run() exists.

How to create Thread -
1.extending Thread Class
2.implementing Runnable Interface
             1.Thread Class -
                                      1.1 - Thread()
                                      1.2 - Thread(String name)
                                      And override run()
             2.Runnable Interface -

                                      2.1 - Thread(Runnable r)
                                      2.2 - Thread(Runnable r,String name)
                                      And  implement run()
                                    
Thread Scheduler -
            It is a part of JVM which decides which runnable thread to run.
There is no guarantee that which thread will be picked by Scheduler to run.
 Only 1 Thread is executed at a time in single Process.

eg.
    Thread  t1 = new Thread();
    Thread  t1 = new Thread();  
//override run()

t1.start()  -> JVM calls run()
t2.start()  -> JVM calls run()

 How to run 2 Threads to print numbers?
void run(){
for(int i=1;i<5;i++)
try {
 Thread.sleep(500);   // sleep for 0.5 sec then go to syso

syso(i + Thread.getCurrentThread.getName());
}
o/p ->1 Thread 0   //for t1
          1 Thread 1   //for t2
          2 Thread 0
          2 Thread 1  
          3 Thread 0 
          3 Thread 1  
          4 Thread 0 
          4 Thread 1      

 What happens if w directly call run() on thread?

    Consider above eg.
    t1.run();
    t2.run();
Directly calling run method does not create Thread Object But Create Normal Object.

o/p-> 1 main    
          2 main
          3 main
          4 main
          1 main
          2 main
          3 main
          4 main
          
Its like running same method twice. 

Can we call same thread Twice?
t1.start();
t1.start();

No.It will throw IllegalThread Runtime Exception.
 
 join() - used to let current thread execute till it dies. Then Executes next Thread.
t1.start();
t1.join() //called join()
t2.start(); 
t3.start(); 
o/p - 1Thread 0
         2Thread 0
         3Thread 0
         4Thread 0  //till t1 finishes
         1Thread 1  //t2
         1Thread 2  //t3
         2Thread 1
         2Thread 2
         3Thread 1
         3Thread 2
         4Thread 1
         4Thread 2          

 
Priority Of Thread -
To set Priority Of Thread -
MIN_PRIORITY        value is 1
NORM_PRIORITY    value is 5
MAX_PRIORITY       value is 10
 eg.
t2.setPriority(MIN_PRIORITY);
t1.setPriority(MAX_PRIORITY);

t1.start();
t2.start();
//Now Thread with Max Priority will be executed first by JVM.
But it always not guaranteed.

Imp Methods -
1.sleep() - makes the thread sleep for  specified time.(Thread changes from running to runnable)
2.yield() - makes the current running thread to allow other threads with same priority to run in same Thread pool.
Eg.  If T Thread pool has total 5 Threads and  T1 ,T2 with same priority of 10.
It we call
t1.start()
t4.start()
t5.start()
t3.start()
t2.start()

Then , while T1 is running it allows T2 also to run because of same Priority in the same pool.
3.Join() - makes the thread complete run() before allowing next Thread to run.
 

No comments:

Post a Comment