Introduction of Thread (Multiprocessing and MultiThreading)

Introduction of Thread (Multiprocessing and MultiThreading)

  1. Java supports single-thread as well as multi-thread operations. A single-thread program has a single entry point (the main() method) and a single exit point. A multi-thread program has an initial entry point (the main() method), followed by many entry and exit points, which are run concurrently with the main(). The term "concurrency" refers to doing multiple tasks at the same time.
  2. Java has built-in support for concurrent programming by running multiple threads concurrently within a single program. A thread, also called a lightweight process, is a single sequential flow of programming operations, with a definite beginning and an end. During the lifetime of the thread, there is only a single point of execution. A thread by itself is not a program because it cannot run on its own. Instead, it runs within a program.

MULTITASKING

By using Multitasking we can perform multiple tasks at a time simultaneously.

    Multitasking is in two ways

  1. By using Threads/ Multithreads
  2. By using processor/ Multiprocessing

MULTIPROCESSING

By using multi processing we can achieve multi tasking. In terms of multiprocessing it is a heavy weight task.


What is Multithreading ?

  1. Multithreading is light weight task/Processing. It means each process having one thread and entire process having one cpu.
  2. Multiprocessing is a heavy weight Processing. It means each process having one cpu.
  3. Compare to multiprocessing, multithread concepts will give more performance. Even maintenance also very less.
  4. Java supports multithreading concept.
  5. Inside java every executable code in java is executed by Threads only .without threads we can’t do anything.
  6. In java there are two types of threads.
    1. Daemon Threads
    2. User Threads

    Daemon Thread: It is a thread; it fully depends on parent life time.

  7. JRE (or) RTE creates only two Daemon Threads.
    1. Garbage Collector
    2. Thread Scheduler
    Note
    • we can’t create any Daemon Thread directly or explicitly

    User Thread: It is a Thread but it doesnot depend on parent Thread life time. In java we can create as many as user threads directly or externally. Even JRE also creates user threads except Garbage Collector and Thread Scheduler.

    Note
    • Once if we create user threads we can convert user threads to daemon threads. But we can’t create daemon threads directly. Once if we trigger java command JRE will create one thread to main method, inside that class the thread is named as “Main Thread”.

    • Java execution starts with main thread and ones if we get main thread then we can able to create as many as child threads. All child threads are user threads only even Main Thread is also an user thread. - User Threads can be invoked explicitly whenever we require. Ones if we invoke user thread it will come to execution with 100% guarantee.

      • We can’t invoke daemon thread explicitly but we can make request to daemon threads but there is no guarantee in executing daemon thread.

      • We can’t command daemon threads.

    • In java we can create threads into two ways

      • By using java.lang.Thread (it is a class)

      • By using java.lang.Runnable (it is Interface)

    Rules for creating threads: It is a Thread but it doesnot depend on parent Thread life time. In java we can create as many as user threads directly or externally. Even JRE also creates user threads except Garbage Collector and Thread Scheduler.

    • We should extend thread class to our class (or) make our class as sub class to Thread class.
    • We should override run() method inside sub class which is inherited from Thread class.

    Example:
    MyThread extends Thread
    {
      public void run()
      {
      }
    }
  8. So user should keep what are the tasks he want to execute with child thread that to be kept under run() method.

  9. Inside main() method create object to sub class by using that, object reference variable will invoke the start() method.

    Example:
    ThreadManager
    {
      MyThread t=new MyThread();
      t.start();
    }
Note
  • start() method is inherited from Thread class. Inside sub class we should not override start(). If we override , class willn’t get thread features.
  • Start() method perform two things
    • Giving thread features to our class object.
    • Invoke run() method (or) assign thread to run().


        
        package com.sdj.pack1;
        class SdjThread
        {
            public void evenNum()
            {
                for(int i=0;i<20;i+=2)
                {
                    System.out.println(“\t”+i);
                }
            }

            public void oddNum()
            {
                for(int i=1;i<20;i+=2)
                {
                    System.out.print(“\t”+i);
                }
            }
        }

        public class ThSample
        {
            public static void main(String[] args)
            {
                SdjThread my = new SdjThread();
                System.out.println("Even Numbers");
                my.evenNum();
                System.out.println("odd Numbers");
                my.oddNum();
            }
        }

        

    Output :


Even Numbers
0 2 4 6 8 10 12 14 16 18
Odd Numbers
1 3 5 7 9 11 13 15 17 19




                               
       package com.sdj.pack1;
       class MyThread extends Thread
       {
          public void run()
           {
                System.out.println("even Number::");
                new A().evenNum();
           }
        }
       class A
       {
          public void evenNum()
          {
             for(int i=0;i<20;i+=2)
             {
                System.out.print(“\t”+i);
             }
          }
          public void oddNum()
          {
             for(int i=1;i<20;i+=2)
             {
                System.out.print(“\t”+i);
             }
          }
       }
       public class ThMyThread
          {
          public static void main(String[] args)
             {
                MyThread t=new MyThread();
                t.start();
                System.out.println("Odd Numbers::");
                new A().oddNum();
             }
          }

                               

    Output :


Odd Numbers:
Even Numbers:
1 3 5 7 0 2 4 6 8 10 12 14 16 18 9 11 13 15 17
(or) Odd Numbers:
Even Numbers:
0 2 4 6 8 10 12 14 16 18 1 3 5 7 9 11 13 15 17 19

Explanation:

  • Until we call start() method to our class(MyThread)we can’t achieve thread features.

  • Once it is called then it gives thread features and load our override run()

  • After finishing start() one more thread comes to the execution

  • Then stack is divided into two parts

  • Child thread execute only run()

  • Main thread execute until main() is finish

  • Child thread(t) acts as part of JRE

Memory Management

javapadho
Note
  • Here one processor and two threads i.e. main thread and t thread
  • If first executed main thread it starts execution if first executed child thread it starts execution
  • Giving thread features to our class object.
  • Once we call start () then object can change from that state i.e. New born state to Runnable state.

Runnable Thread: It is a pool. Store all threads. These threads are all waiting for CPU time because CPU allows one thread at a time.

If Runnable have 2 threads

  1. CPU loads first thread and give 2sec time here 2nd thread is in waiting state and thread 1 is go to running state then it executes some statements like 6 statements then the time is completed.
  2. Then CPU load 2nd thread give time is 6sec then thread 1 is in wait under Runnable state until 2nd thread execution is complete. Once time is finished then thread 2 goes to Runnable state then again thread 1 comes to running state and execute some statements within the CPU time.
  3. This procedure continues until two threads finish their execution.
  4. Note
    • Once thread execution is complete it is goes to death state.

Methods inside Thread class

  • getName()
  • getId()
  • getPriority()
  • setName()
  • setPriority()
  • isDaemon()
  • isAlive()
  • isInterrupted()
  • interrupted()
  • yield()
  • sleep()
  • run()
  • start()
  • stop()
  • setDaemon() etc..
  • getName():

    To get the name of the thread name

  • getId():

    To get the name of the thread ID

  • setName(String s)

    To set the thread name in two ways

    • through constructor
    • using setName() method
    • Note
      • But for main thread we can’t set the name through constructor because for that thread we are not creating object. It is created by JRE.
      • But we can set through setName().
  • setPriority():

    To set the priority of the thread in between 1 to 10 only.

  • yield():

    One of the important methods inside Thread class. It brings current thread from running state to runnable state forcefully even CPU time finished or not.




                               
   package com.sdj.pack1;
   class OddPrinter extends Thread
   {
      public void run()
      {
         for(int i=0;i<=20;i+=2)
         {
            System.out.println(getName()+" "+i);
            currentThread().yield();
         }
      }
      OddPrinter(String threadName)
      {
         super(threadName);
      }
   }
   class EvenPrinter extends Thread
   {
      public void run()
      {
         for(int i=0;i<=20;i+=2)
         {
            System.out.println(getName()+" "+i);
            currentThread().yield();
         }
      }
      EvenPrinter(String threadName)
      {
         super(threadName);
      }
   }
   public class ThMethods
   {
      public static void main(String[] args)
      {
         OddPrinter t=new OddPrinter("Odd Number");
         System.out.println(Thread.currentThread().getName());
         EvenPrinter t1=new EvenPrinter("Even Number");
         t.setName("SDJ");
         t.start();
         t1.start();
         Thread.currentThread().setName("main java thread");
         System.out.println(Thread.currentThread().getName()+"end");
      }
   }


                               

    Output :


main main java threadend SDJ 0 Even Number 0 SDJ 2 Even Number 2 SDJ 4 Even Number 4 SDJ 6 Even Number 6 SDJ 8 Even Number 8 SDJ 10 Even Number 10 SDJ 12 Even Number 12 SDJ 14 Even Number 14 SDJ 16 Even Number 16 SDJ 18 Even Number 18 SDJ 20 Even Number 20



                               
    package com.sdj.pack1;
    class T1 extends Thread
    {
        public void run()
        {
            System.out.println("i am in T1 run");
          System.out.println("my name is : "+getName());
          System.out.println("my priority is:: "+getPriority());
       }
    }
    class T2 extends Thread
    {
        public void run()
       {
           System.out.println("my name is: "+currentThread().getName());
          System.out.println("my priority is: "+getPriority());
       }
    }
    public class ThMethods1
    {
       public staticvoid main(String[] args)
           {
              T1 t1=new T1();
              T2 t2=new T2();
              System.out.println("Hai i am :: "+Thread.currentThread().getName()+"::"+"my priority is: "+
              Thread.currentThread().getPriority());
              t1.setPriority(8);
              t2.setPriority(10);
              t1.start();
              t2.start();
          }
      }                               

    Output :


Hai i am :: main::my priority is: 5 i am in T1 run my name is : Thread-0 my priority is:: 8 my name is: Thread-1 my priority is: 10

Explanation:

  • To get main thread features i.e. name, priority etc. We should give Thread.currentThread().getName()

  • If we don’t set priority to child thread then it will display parent thread priority i.e. main. Default main thread priority is 5

  • setPriority(1 to 10 only)

  • It is a method to setpriority from1 to 10 only i.e. min to max priority

  • If we give other than 1 to 10 like -1 or 11 etc it will give run time Exception i.e. IllegalArgumentException

    • MAX_PRIORITY=10
    • MIN_PRIORITY=1
    • NORM_PRIORITY=5