Thread:-

Thread is a collection of light-weight subprocess to execute the program. when we execute any program then it will use multiple collections of subprocess to run the program.


By Default, every Java Program uses thread because main() is the default Thread for Java Program.


MS-World is the best example of thread because we can type content and spell checker both will work simultaneously.


We will use thread to implement multithreading program. using multithreading we can perform multi-tasking operation using this we can execute multiple processes simultaneously.

Multithreading reduces resource and performs multiple tasks.


Thread life cycle:-

Thread uses multiple stages to perform the operation.

1 Init State:-  when we create a Thread Object.

2 Ready State:- Thread is ready to execute with functionality.

3 Runnable State:- when we start a thread using thread().

4 Interruption State or waiting for the state:-  when we use sleep() or wait() in Thread.

5 Dead State:-  when we close the threading process.










Thread Program using Thread Class:-

Class Classname extends Thread
{
     public void run()
     {

     }

}

Classname obj = new Classname();
obj.start();  //run method will be called



public class ThreadExample extends Thread {
    public void run()
    {
        for (int i = 1; i <= 10; i++) {
            try
            {
            System.out.println("Process "+i);
            Thread.sleep(1000);  //interruption state
            }
            catch(InterruptedException ex)
            {
             
            }
        }
    }
    public static void main(String[] args) {
        ThreadExample obj = new ThreadExample();  //init state
        obj.start(); //runnable state
         ThreadExample obj1 = new ThreadExample();  //init state
        obj1.start(); //runnable state
    }
 
}



Limitation of Thread Class:-

Using Thread Class we can not perform multiple inheritances means if we require Thread Feature and Other Class Features both in a Single class then it is not possible with Thread Class.

class A
{

}

class B extends Thread,A  //error
{

}


Java provides Runnable Interface to implement Thread Features in Program:-

class Classname implements Runnable
{

   public void run()
   {

    }   


}

run() is the abstract method of Runnable Interface hence it must be overridden into the implemented class.

using this we can perform multiple inheritances also.

class A
{

}

class B extends A implements Runnable  //Multiple Inheritance
{


}


..........................................................................


Example of Thread using Runnable Interface:-

............................................................................................................



class A    //Normal Class
{
    String displayHello()
    {
        return "A class";
    }
}

public class ThreadExample3 extends A implements Runnable  //multiple inheritance  {

    ThreadExample3()
    {
        Thread t = new Thread(this);  //manually create Thread Class Object
        t.start();
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try
            {
            System.out.println(super.displayHello());
            Thread.sleep(1000);
            }
            catch(InterruptedException ex)
            {
             
            }
        }
    }
 
    public static void main(String[] args) {
        ThreadExample3 obj = new ThreadExample3();
    }
}


.........................................................................................................................................................

Q)How we get the name of Current Thread?

Ans:- Thread.currentThread().getName()

Q)What is the difference between Thread and Runnable?

Ans:-  Thread is class but runnable is the interface. Thread class provide complete features but Runnable interface provide set of rules which will be implemented by the child class.

...............................................................................................................................................................

Join() in Thread:-

It is used to join the execution of all scheduled thread one by one, join() will join another thread when current thread execution will be completed .join() will automatically join waiting for thread in order.

for example, if three thread is executing 0,1 and 2 then join() will wait for 1 and 2 thread and execute 0 thread when it will complete the process then second  1 thread will executed when it will complete then the 2-second thread will execute.



join() is generally used to call thread from waiting for the state to runnable state.


Thread1 obj = new Thread1();
obj.start();
obj.join(5000);
Thread1 obj1 = new Thread1();
obj1.start();

if we do not provide time in join() then another will wait till complete execution of the current thread.
if we provide time in join() then it will join another thread after completion of join time.


Example of Join() in Java?


public class ThreadExample extends Thread {
    public void run()
    {
        for (int i = 1; i <= 10; i++) {
            try
            {
            System.out.println("Process "+i);
            Thread.sleep(1000);  //interruption state
            }
            catch(InterruptedException ex)
            {
             
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        ThreadExample obj = new ThreadExample();  //init state
        obj.start(); //runnable state
        obj.join();
         ThreadExample obj1 = new ThreadExample();  //init state
        obj1.start(); //runnable state
    }
 
}

...............................................................................................................................................

Q)what is the difference between sleep() and join()?

A) sleep() is used to pause the subprocess of currently executing thread and join() is used to wait for another thread excluding currently executing the thread.
sleep() can be used in normal thread means in single thread system and multithreaded system both but join() will only use in multithreaded System.


.............................................................................................................................................................

Thread Synchronization:-
............................................................................................................................................................

Using this we can synchronize Thread Process Step by Step. It will execute the first thread process after that second thread process will be executed.

It will synchronize a complete block of code of an application.

for Thread Synchronization, we will use the synchronized keyword to perform thread synchronization operation.


Example of Thread Synchronization:-




class Table
{
 
   
    synchronized public void displayTable(int num)
    {
        for (int i = 1; i <= 10; i++) {
            try
            {
            System.out.println(num*i);
            Thread.sleep(1000);
            }
            catch(Exception ex)
            {
             
            }
        }
    }
}
class Thread1 extends Thread
{
   Table t;
   Thread1(Table t)
   {
       this.t=t;
   }
   public void run()
   {
       t.displayTable(5);
   }
}
class Thread2 extends Thread
{
    Table t;

    public Thread2(Table t) {
        this.t=t;
    }
    public void run()
   {
       t.displayTable(9);
   }
 
}

public class ThreadExample22  {
    public static void main(String[] args) {
        Table t = new Table();
        Thread1 t1 = new Thread1(t);
        t1.start();
        Thread2 t2 = new Thread2(t);
        t2.start();
    }
 
}


.............................................................................................................................................

wait():-  this method will only be used under the synchronized block. when we use synchronized keyword then the current thread process will be locked and released when the thread will be completed.
but when we use wait() then Thread monitor will be in waiting state and thread will be executed with normal thread execution.

means if we want to synchronize thread process for particular time then we can use wait().


notify():-
it is used to provide alert or notification to interrupted thread process.
and wait time will be removed after notify()


Synchronized block:- if we want to synchronize a particular set of code of method then we can create a synchronized block.

class Table
{
 
   
     public void displayTable(int num)
    {
        synchronized(this)
        {
        for (int i = 1; i <= 10; i++) {
            try
            {
            System.out.println(num*i);
            //wait(1000);
         
            Thread.sleep(1000);
            notify();
            }
            catch(Exception ex)
            {
             
            }
        }
            System.out.println("hello");
            System.out.println("welcome");
        }
    }
}



notify all():-  it will alert all waited thread of Program.


Daemon Thread:-

This thread is used to run all user define thread, it is also called background thread which will be by default managed by the operating system.

When we start any program in system then daemon thread will automatically be created and run till last.


we can convert user define thread to Daemon thread using setDaemon()

        ThreadExample obj = new ThreadExample();  //init state
        obj.setDaemon(true);
        obj.start(); //runnable state
     






Yield():-  it is used to process switching based program when we want to change the state of currently executed thread to ready state and pass another thread process for execution then we can use yield().

when we apply thread priority then yield() will be internally called because it will execute higher priority thread first and lower priority thread to last.


yield() is also depend on o/s busy schedule hence sometimes it can not work if o/s schedule is not managed internally.



Ready State to Runnable State----->  start()

Runnable State to not runnable state ---> sleep()

Runnable to Ready State  -------> yield()



























































Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post