Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

Thread Concept in Java?
...........................................................................................................

Thread is a collection of light-weight subprocess to execute the program, Java each program managed by the main thread because Java program execution will be started by main().

Thread Concept generally used to provide a multi-threading system in an application.

Multithreading is the subpart of multitasking using this we can execute multiple processes under a single resource. we can save the resource for application.


For example, if we assign multiple tasks to a single developer at the same time that is called multithreading.

if we assign five different tasks to five different developers at the same time that is not multithreading, it is called multiprocessing.

Multithreading saves resources (memory, effort,  time) but multiprocessing takes more resources as compare to multithreading.



Thread life cycle:-

When we create a thread program manually in Java then the thread objects will follow various groups of states step by step.

1) init state:-   when we create Thread class object then it is in init State


2)  ready state:-   It is the Thread state before thread execution


3)  runnable state:- 
When we call start() then the thread will be in a runnable state


4)   not runnable state:-  when we call wait() or sleep() then the thread will be in a non-runnable state


5)   completion state or termination state:-  When the threading process will be completed then the thread will be in completion state.







Create a Simple Program to implement the Single Thread process:-


class ThreadExample extends Thread
{
   public void run()
   {
       for(int i=1;i<=10;i++)
       {

             try
             {
             System.out.println(i);
             Thread.sleep(1000);

             }

             catch(Exception ex)
             {

             }
       }

   }

public static void main(String args[])
{
    ThreadExample obj = new ThreadExample();
    obj.start();

}
}

How many ways to implement Thread?

We can implement Thread using two different ways

1)  using Thread Class:-

     class Classname extends Thread
   {
           public void run()  //   optional
          {

          }
   }

limitation:-  Thread class can not manage multiple inheritances. for example, we want to extend any other class functionality as well as Thread functionality then it is not possible by Thread class.

2)  using Runnable Interface:-

This is the interface which provides run() to manage the running state of the thread, we can easily perform multiple Inheritance using Runnable Interface.

class Classname implements Runnable    //it is not complete thread class
{
        Classname()
       {
            Thread  t= new Thread(this);   //Mandatory to create thread object
            t.start();

       }
        public void run()      //mandatory
        {

        }

}


Example of the runnable interface:-

class A
{
    public String display()
    {
       return "A";
    }
}

class ThreadExample2  extends A implements Runnable
{
      ThreadExample2()
      {
           Thread t = new Thread(this);
           t.start();
      }

      public void run()
      {
          for(int i=1;i<=10;i++)
          {
              try
              {
                  System.out.println(i+super.display());
                  Thread.sleep(1000);
              }
              catch(InterruptedException ex)
              {

              }
          }

      }

  public static void main(String args[])
  {
       ThreadExample2 obj = new ThreadExample2();

  }


}


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

Type of Thread:-

1) Single Thread:-  using this we will start one thread process at a time means if we create only one thread object and start them then it is called Single Thread.
 public static void main(String args[])
  {
       ThreadExample2 obj = new ThreadExample2();
    

  }

2)  MultiThread:-   using this we can execute multiple Thread processes at the same time and the same resource then it is called multithreading.

if we create multiple Thread Object and start the threading process then it will implement the multithreading concept.


By default multithreading process provide parallel execution, using Thread Synchronization we can provide a Multithreading parallel process to step by step.


The program is the same only we create multiple objects.

 public static void main(String args[])
  {
       ThreadExample2 obj = new ThreadExample2();
       ThreadExample2 obj1 = new ThreadExample2();
       ThreadExample2 obj2 = new ThreadExample2();

  }



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

Thread Synchronization:-


Using this we will perform step-by-step execution of parallel thread means when one thread will be executed completely then another thread will be started.

Thread Synchronization will be implemented by Synchronized keyword using the Synchronized method and Synchronized block.

Example of Thread Synchronization:-

class Table
{
   int num;
   synchronized void displayTable(int num)
   {
        for(int i=1;i<=10;i++)
        {
              try
              {
              System.out.println(num*i);
              Thread.sleep(1000);
              }
              catch(InterruptedException ex)
              {

              }

        }


   }


}

class Thread1 extends Thread
{   Table t;
    public 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);
   }

}

class ExecuteThread
{

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

Program to implement wait() and sleep() simultaneous in Single Program?

class Table
{
   int num;
   synchronized void displayTable(int num)
   {
        for(int i=1;i<=10;i++)
        {
              try
              {
              System.out.println(num*i);
              //Thread.sleep(1000);
                if(i>=5)
                wait(1000);
                else
                Thread.sleep(1000);
              }
              catch(InterruptedException ex)
              {

              }

        }


   }


}

class Thread1 extends Thread
{   Table t;
    public 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);
   }

}

class ExecuteThread
{

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

Synchronized block example:-

if we want to synchronize a particular line of code of method then we can use a synchronized block.

because if we create a synchronized method then the complete method code will be synchronized, we can create more then one synchronized block in a single method.



class Table
{
   int num;
   void displayTable(int num)
   {
       synchronized(this)
       {
        for(int i=1;i<=10;i++)
        {
  
              try
              {
              System.out.println(num*i);
              //Thread.sleep(1000);
                if(i>=5)
                wait(1000);
                else
                Thread.sleep(1000);
              }
              catch(InterruptedException ex)
              {

              }

        }
      }

   }


}

class Thread1 extends Thread
{   Table t;
    public 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);
   }

}

class ExecuteThread
{

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

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


1 ) notify() and notifyAll():-  It is used to notify waiting for a time interval of thread means if we provide notify() under wait() then wait time will be finished automatically.

notify all() will resume all waiting state thread in application.it can be used with multiple synchronized blocks under thread.


Example of notify()


class Table
{
   int num;
   void displayTable(int num)
   {
       synchronized(this)
       {
        for(int i=1;i<=10;i++)
        {
  
              try
              {
              System.out.println(num*i);
             
                wait(3000);
                notify();
             
              }
              catch(InterruptedException ex)
              {

              }

        }
      }

   }


}

class Thread1 extends Thread
{   Table t;
    public 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);
   }

}

class ExecuteThread
{

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


Join():-  join is used to merge the process of thread, but it will merge another thread process when the currently executing thread will be completed.


Thread t1 = new Thread();
Thread t2 = new Thread();

t1.start();
t1.join();
t2.start();



Example of join():-

class ThreadExample extends Thread
{
   public void run()
   {
       for(int i=1;i<=10;i++)
       {

             try
             {
             System.out.println(i);
             Thread.sleep(1000);

             }

             catch(Exception ex)
             {

             }
       }

   }

public static void main(String args[]) throws InterruptedException
{
    ThreadExample obj = new ThreadExample();
    obj.start();
    obj.join(1000);
    ThreadExample obj1 = new ThreadExample();
    obj1.start();

}
}




Daemon Thread:-   It is called System Thread because it is used to execute all User-Define Thread under the application. Daemon Thread will be the Primary Thread of Java Application.

Java call garbage collector using the daemon thread method. This thread will be started automatically in the System and provide background support to all UserDefine Thread.

We can convert user-defined thread to daemon Thread using setDaemon().
 

Example of Daemon Thread:-

class ThreadExample extends Thread
{
   public void run()
   {
       for(int i=1;i<=10;i++)
       {

             try
             {
             System.out.println(i);
             Thread.sleep(1000);

             }

             catch(Exception ex)
             {

             }
       }

   }

public static void main(String args[])
{
    ThreadExample obj = new ThreadExample();
    obj.setDaemon(true);
    obj.start();
   
   
    ThreadExample obj1 = new ThreadExample();
    obj1.start();

}
}


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