Java is a programming language that supports multithreaded programs. Multithreaded programs accommodate two or more parts (threads) that run simultaneously, handling different tasks, enabling optimal CPU usage. Multi-threading is an extension of multi tasking. Multi tasking can be defined as a feature where multiple processes share a common processing resource like a central processing unit.Â
Multithreading branches out the concept of multi-tasking to various applications where defined operations can be broken down into smaller individual threads.
Each of these threads runs simultaneously and independently with different execution paths such that an exception in one thread does not affect the performance of others.Â
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.
What is Multithreading in Java?
Multithreading in Java is where multiple threads are executed simultaneously to maximize the CPU time.
Life Cycle of a Thread
Threads have different stages in their life cycle. They are as follows:
- New:Â The thread begins its life cycle as a new thread. It remains in this newborn stage until a program runs the thread.Â
- Runnable:Â A born thread enters the runnable stage when a program initiates it. The thread starts executing its task in this stage.
- Waiting:Â This is a transition stage where a thread waits for another thread to complete its task. A thread in the waiting stage switches to a runnable stage after receiving a signal from other threads.
- Timed waiting:Â This is a stage that a runnable thread can enter for a specific time interval. Threads in this stage move back to the runnable stage at the end of the specific time interval.Â
- Dead:Â This is the final stage in the life cycle of a thread. A thread enters this stage after completing its task.Â
Benefits of Multithreading in Java
- As threads in Java are independent, Java multithreading does not block the users, and they can perform many operations simultaneously.Â
- As multithreading in Java enables multiple operations, it is time-saving and efficient.Â
- The program can run continuously even if a part of it is intercepted.
- It improves the performance against the conventional parallel programs that use multiple processes.
- Creation of efficient programs that utilize the CPU time to its fullest.
- Greatly improves the response time of complex applications.Â
- Requires fewer resources compared to traditional parallel programs.
Order of Thread Priority
The operating system determines the thread’s execution schedule based on the thread’s priority. A thread’s priority is determined based on its constant’s value.Â
- Constant 1 gets minimum priority ( MIN_PRIORITY)
- Constant 5 gets normal priority ( NORM_PRIORITY)
- Constant 10 gets the maximum priority (MAX_PRIORITY)
Popular Courses & Articles on Software Engineering
How to create a thread in Java?
Threads can be created in Java in two ways:
- Extending thread class
- Implementing a runnable interface
Creating a Thread by Extending Thread Class
A few methods of thread class and their functions are given below.Â
- getName() : For obtaining thread’s name
- getPriority(): To obtain thread’s priority
- is Alive(): to find if a thread is runningÂ
- join(): wait for a thread’s termination
- run() : Point of thread’s entry
- sleep(): For suspending a thread for a specific time window.
- start() : To activate a thread through its run() method.
Step 1: Override the run() method given in the thread class. This acts as the entry point for the thread, and the entire program logic should be encased in 4this.Â
The syntax of the run() method is as follows:
public void run ( )
Step 2:Â Â Initiate the thread object by start () method whose syntax is a void start ( ).Â
Here are examples of a multithreading program in Java:
Example 1:
class MultithreadingDemo extends Thread{Â Â
  public void run(){ Â
   System.out.println(“My thread is running.”); Â
  } Â
  public static void main(String args[]){ Â
   MultithreadingDemo obj=new MultithreadingDemo(); Â
   obj.start(); Â
  } Â
}
The output of the above program will be:
My thread is running.
Example 2:Â
class Count extends Thread
{
  Count()
  {
   super(“my thread is extending”);
   System.out.println(“my thread is created” + this);
   start();
  }
  public void run()
  {
   try
   {
     for (int i=0 ;i<10;i++)
     {
      System.out.println(“Printing the count ” + i);
      Thread.sleep(1000);
     }
   }
   catch(InterruptedException e)
   {
     System.out.println(“my thread got interrupted”);
   }
   System.out.println(“My thread is over” );
  }
}
class ExtendingExample
{
  public static void main(String args[])
  {
    Count cnt = new Count();
    try
    {
     while(cnt.isAlive())
     {
      System.out.println(“Main thread will be alive till the child thread lives”);
      Thread.sleep(1500);
     }
    }
    catch(InterruptedException e)
    {
     System.out.println(“Main thread got interrupted”);
    }
    System.out.println(“Main thread’s run is terminated” );
  }
}
The output of the above program will beÂ
my thread is createdThread[my runnable thread,5,main]
Main thread will be alive till the child thread lives
Printing the count 0
Printing the count 1
Main thread will be alive till the child thread lives
Printing the count 2
Main thread will be alive till the child thread lives
Printing the count 3
Printing the count 4
Main thread will be alive till the child thread lives
Printing the count 5
Main thread will be alive till the child thread lives
Printing the count 6
Printing the count 7
Main thread will be alive till the child thread lives
Printing the count 8
Main thread will be alive till the child thread lives
Printing the count 9
my thread run is terminated
Main thread run is terminated
Creating a Thread by Implementing a Runnable Interface
There are three important steps to be followed while using this method.Â
Step 1: A run() method should be implemented by a runnable interface. This run() method acts as the entry point for the thread and should contain the entire program logic.Â
Syntax for the run() method isÂ
public void run( )
Step 2:Â Â A thread object should be activated using the constructor given below.
Thread(Runnable threadObj, String threadName);
Here threadObj acts as the class that implements the runnable interface, and thread name is the name given to the new thread.
Step 3: After creating the thread object, it can be initiated by the start() method that executes the run() method.Â
The syntax of the start () method is as follows.
void start();
An example of creating a thread by implementing a runnable interface can be found here.
To learn more about Java multithreading and software development, we recommend enrolling in the Executive Post Graduate Program in Software Development offered by IIIT Bangalore in association with upGrad.
Executive PG Program in Software Development is a 13-month online program designed to help working professionals take a giant leap in their careers through industry-relevant case studies and projects. The program also includes over ten live sessions from the industry experts to help the candidates learn better.Â
The program includes industry projects to help the candidates have hands-on experience and adequate industry exposure to make their learning relevant and practical. The completion of the program will reward the candidates with the coveted IIIT B certification and alumni status.Â
The program comes with 360-degree placement support from upGrad that has impacted over 40,000 paid learners from all corners of the world to make things even better. upGrad has a learners base from over 85 countries providing a priceless opportunity to have a global peer network for the candidates.Â
What is the difference between multitasking and multithreading in Java?
Multitasking is the process by which many tasks can be performed simultaneously, and multithreading is the process of executing multiple threads at the same time, with each thread performing a different task.
Is multiple inheritance supported by Java?
The programming language Java supports multiple inheritance, a process in which a class implements more than one interface. A class can have different implementations of a method (default or static) in the interfaces. Multiple inheritance in Java can be implemented only with interfaces and not classes, unlike the C++ language.
Can multithreading improve the performance of Java?
Multithreading improves the performance of Java by enabling multiple CPUs to attend to the same issue. This not only speeds up the process but also helps in efficient problem-solving.
