What is Multi-Threading in Java?

  • Executing more than one thread simultaneously is called as multithreading.
  • Multithreading is best suitable at the User Application level.
  • Multithreading allows running two or more parts of the programs concurrently.

Example:
Multithreading
In the above picture, for each deposit or withdraw, separate threads will be allotted for each user.

Watch this Java Video

Multithreading in Java What is Multi-Threading in Java? Executing more than one thread simultaneously is called as multithreading. Multithreading is best suitable at the User Application level. Multithreading allows running two or more parts of the programs concurrently. Example: In the above picture, for each deposit or withdraw, separate threads will be allotted


Thread Creation

Threads can be created in two ways:

  • By extending java.lang.Thread class
  • By implementing java.lang.Runnable interface

Get ready for the high-paying Java jobs with these Top Java Interview Questions and Answers!

By extending Thread class

  • Define your own thread class by extending java.lang.Thread class.
  • Override the run() method with the following signature public void run()
  • Write the logic required for your thread inside the run() method.
  • Create the object of your own thread class.
  • Call the start() method using your own thread object.
classThreadingCheck extendsThread {
publicvoidrun(){
try{
System.out.println (“Thread is running”);
}
catch(Exception e)
{
System.out.println (“Caught Exception”);
}
}
}
publicclassIntellipaat{
publicstaticvoidmain(String[] args) {ThreadingCheckth1 = newThreadingCheck();
th1.start();
ThreadingCheckth2 = newThreadingCheck ();
th2.start();
}
}

Output:
Thread is running
Thread is running

By implementing java.lang.Runnable interface

  • Define your own thread class by implementing java.lang.Runnable interface.
  • Override the run() method with the following signature public void run()
  • Write the logic required for your thread inside the run() method.
  • Create the object of your own thread.
  • Create the object of java.lang.Thread by passing your own thread object as parameter to constructor.
  • Call the start() method using your own thread object.

Program to start the same thread twice:

classThreadingCheckimplements Runnable{
publicvoidrun(){
try{
System.out.println (“Thread is running”);
}
catch(Exception e)
{
System.out.println (“Caught Exception”);
}
}
}
publicclassIntellipaat{
publicstaticvoidmain(String[] args) {Thread ob=new Thread(newThreadingCheck ());
ob.start();
ob.start();
}
}

Output:
Thread is running
Thread is running

Know the major differences between today’s most prominent languages in the IT industry, check out this Java vs Python blog!

Thread Sleeping

sleep() is a method in Thread class that is used to sleep the currently running thread for few milliseconds.

import java.lang.*;public class ThreadSleep implements Runnable
{
Thread t;
public void run(){
for (int i = 0; i<3; i++)
{
System.out.println(Thread.currentThread().getName()
+ ” ” + i);
try{
Thread.sleep(1000);
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}public static void main(String[] args) throws Exception{
Thread t = new Thread(new ThreadSleep());
t1.start();Thread t2 = new Thread(new ThreadSleep());
t2.start();
}
}

Output:
Thread-0  0
Thread-1  0
Thread-0  1
Thread-1  1
Thread-0  2
Thread-1  2

Thread Scheduler

Thread scheduler contains the pool of threads. When threads are started in a program by start() method, then each thread is kept in thread scheduler.
There is no assurance to which thread will get the chance first in the processor. Thread with more priority will be operated first.
JVM has some threads for the execution of a program:

  • Main: main is a method but actually, it is a thread for JVM from where the execution starts.
  • Garbage Collector(gc()): gc() is a thread that checks after each thread for a garbage value.
  • Timer thread: timer threads maintain the time of each thread like wait(), sleep(), etc

Thread schedular

 

If you have any doubts or queries related to Java, get them clarified from the Java experts on our Java Community!

Thread Joining

  • This allows to wait one thread until the task of other thread is completed.
  • join() is a method used for thread joining.
  • In main thread -> t1.join()

Main thread will be joined at the end of t1.

  • In t1 thread -> t2.join

T1 thread will be joined at the end of t2.

import java.io.*;
class ThreadJoin extends Thread{
public void run(){
for (int i = 0; i< 2; i++){
try{
Thread.sleep(500);
System.out.println(“Thread: “+ Thread.currentThread().getName());
}
catch(Exception ex)
{
System.out.println(“Exception caught”);
}
System.out.println(i);
}
}
}
class Intellipaat{
public static void main (String[] args)
{
ThreadJoining t1 = new ThreadJoining();
ThreadJoining t2 = new ThreadJoining();t1.start();
try{
System.out.println(“Thread: ”+ Thread.currentThread().getName());
t1.join();
}
catch(Exception ex)
{
System.out.println(“Exceptioncaught”);
}t2.start();
try
{
System.out.println(“Thread: ”+ Thread.currentThread().getName());
t2.join();
}catch(Exception e){
System.out.println(“Exception caught”);}
}
}

Output:
Thread: main
Thread: Thread0
Thread: Thread0
1
Thread: main
Thread: Thread1
Thread: Thread1
1

Want to know why majority of Java Developers are moving towards Hadoop? Get to know in this 7 Reasons You Should Switch Career From Java to Hadoop blog!

Life Cycle of a Thread
Lifecycle of thread

  • NEW Thread

When you create the thread, then Thread state is NEW.

  • Runnable

When you start the thread, then will be placed in Ready To Run state and it will wait for CPU time.

  • Running

Depending on the CPU Scheduling algorithm, thread will move from Ready to Run state to Running state or Running state to Ready to Run. When thread is in Running state then it will utilize CPU time, i.e. thread will execute its run() method tasks.

  • Sleep()

When you call sleep() method then the current running thread moves to Sleeping state. Thread will remain in sleep state for a specific time. Once the thread’s sleep will be over, it will move to Ready to Run state automatically. Sleep state is also called timed waiting state.

  • wait()

When you call wait method, then the currently thread move to wait state till you call method notify() or notifyAll() or when the specific time is over.

  • Blocked State

When a running thread is requesting unavailable resources then thread will move to block state. Thread in Block state will move to Ready to Run state when requested resources is available.
Blocked states may lead to deadlocks.
Consider the following case:
Deadlocks

  • In the above case, process P1 by holding the resources R1 requesting for resource R2 and P1 will complete its execution only when P1 gets resource R2.
  • Similarly, process P2 by holding the resources R2 requesting for resource R1 and P2 will complete its execution only when it gets resource R1.
  • So, here, both processes are requesting for unavailable resources. Both will be placed in Blocked state and both will not come out of Blocked state. This situation is called as Deadlock.

Deadlock
In the above case,

  • Thread 1 demands resource-2(Hostage) but criminal’s friend owns the lock.
  • Thread 2 demands resource-1(Criminal one) but cop owns the lock.

In this situation, no one will act first because each of them is waiting for others to release first. This is called Deadlock.

Conclusion

This brings us to the end of Multi-Threading. In this tutorial, we learned in detail about the overview of Multi-Threading.
We also covered almost all the main parts of Multi-Threading. If you want to learn more, I would suggest trying our Intellipaat “Java” course that covers in-depth knowledge of most of the important topics like Basics of Java, Array, Exception Handling, Multi-threading, etc. to make you a good Java programmer.
Join Intellipaat Java training course and Certification today and let your career boom towards the domain of Software Developer.

Enrol yourself in Online Java Training and give a head-start to your career in Java!

Recommended Videos

Leave a Reply

Your email address will not be published. Required fields are marked *