Learn ABC of Java Multithreading With Examples

Greetings friends, in this post we are going to explain the Java multithreading concept along with state-of-the-art illustrations so that you can learn it quickly. It is one of the most interesting topics which is also the interviewer’s favorite subject for discussion with developers at all levels. We’ve tried to bring almost every little detail in this Java multithreading tutorial so that you can even refer it as an A-Z guide while preparing for any Java interview.

Here, you will see everything related to Java Multithreading starting from very basic concepts of what is a thread, what is thread life cycle, how to create threads in Java by extending Thread class and implementing Runnable interface. Additionally, we’ll supplement all the thread concepts using examples and code samples.

In the 2nd part of this Java multithreading tutorial, we’ll cover Synchronization, Synchronization problems (like deadlocks), Inter-thread Communication via wait/notify/notifyAll, scheduling (with or without Thread priority), Thread interruption, and Thread Groups.

Let’s now get started and explore the world of multithreading.

1- Java multithreading tutorial – Basics.

1.1- Basics of Java multithreading.

1.1.1- What is a process?

A process consists of a memory space allocated by the operating system that can contain one or more threads. The thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.

1.1.2- What is a thread?

  • The thread is a lightweight sub-process and the smallest unit of execution.
  • Each thread has a separate path of execution.
  • It shares the memory area of the process.

1.1.3- What is Java Multithreading?

  • It’s a process of executing multiple threads simultaneously.
  • It enables a process to run its tasks in parallel mode on a single processor system.

Now one question you may ask that what made this concept so popular. To get clarity, let’s see the some of the benefits of using multithreading.

Java Multithreading Tutorial - Java Process and Threads

Java Process and Threads

1.1.4- List out the advantages of Java Multithreading?

  • General – It allows better use of system resources.
  • An important one – It allows parallel execution of tasks and thus saves execution time.
  • It provides enhanced performance on multi-processor machines.
  • Improvised GUI responsiveness.
  • Threads are independent and do not impact other threads of the same process if an exception occurs.

Multithreading doesn’t always yield benefits. It comes with its disadvantages too. Let us go through some of the typical after results.

1.1.5- List out the disadvantages of Java Multithreading?

  • General – It results in the increased complexity of the code.
  • Synchronization of shared resources (objects, data) is CPU/memory intensive.
  • Debugging is hard because sometimes you can’t predict the results.
  • Increased potential for deadlock occurrence.
  • “Starvation” some of the threads may not be served with due to poor design.

1.2- Thread lifecycle in Java.

What is a thread lifecycle in Java? Explain its different stages?

Java Multithreading Tutorial - Java Thread Life Cycle

Java Thread Life Cycle

Before moving on to creating a thread, we’ll first see the various phases through which the thread has to pass to complete its lifespan.

  • New
  • Runnable
  • Running
  • Non-Runnable (blocked)
  • Terminated

New: A thread is in New state when you create the instance of thread class but the start() method is yet to get called.

Runnable: The thread is in runnable after executing the start() method. In this stage, it waits for the thread scheduler to run it.

Running: A thread picked by the thread scheduler for execution remains in running state.

Non-Runnable (blocked): In this state the thread is still alive, but it is not eligible to run. It may be due to some sleep operation, waiting for any File I/O to finish or in the locked state, etc.

Terminated: A thread is said to be in terminated state when its Run() method exits.

So far, you’ ve read the basic concepts of Java multithreading, let’s now move to learn the different ways to create threads.

Creating threads in Java.

In Java, we’ve got the following two ways to create threads.

It is important to learn that Java has supplied most of the thread functionality into the Thread class. So, before we jump to the thread creation part, let’s first understand the different features and methods available in the Thread class.

1.3- Java Thread Class methods, usage, and examples.

Java accomplishes multithreading through its java.lang.Thread class. To become efficient in writing the multithreaded code you must know about the constructors and the methods of thread class before starting to write multithreading programs in Java.

1.3.1- List of Thread class Constructors.

Thread class has the following eight constructors.

Thread(): It creates a Thread object with a default name.

Thread(String name): It creates a Thread object with a name that the name argument specifies.

Thread (Runnable target): This method constructs Thread with a parameter of the Runnable object that defines the run() method.

Thread (Runnable target, String name): This method creates Thread with a name and a Runnable object parameter to set the run() method.

Thread(ThreadGroup group, Runnable target): It creates Thread object with a Runnable object and the group to which it belongs.

Thread (ThreadGroup group, Runnable target, String name): It creates Thread object with a Runnable object that defines the run() method, specified name as its name and the Thread object belongs to the ThreadGroup referred to by the group.

Thread(ThreadGroup group, String name): It creates a thread that has the specified name and associates to the ThreadGroup given as the first parameter.

Thread(ThreadGroup group, Runnable target, String name, long stackSize): this constructor specifies the ThreadGroup parameter, the size of the thread’s method-call stack.


1.3.2- General methods to manage the Threads. start():

When program calls start() method a new Thread is created and code inside run() method is executed in new Thread. run():

This method is Entry point for the thread.

Let’s see a sample code that shows how to use the start() and run() methods. String getName():

You can use this method to get the name of the current thread. setName(String name):

You can use to set the name of the thread.

During a debugging session, it’s helpful as we can distinguish between threads. By default, Java also sets the label for each Thread. Alternatively, you can also give a name to the Thread using the Thread constructor that takes the name as an argument. The method setName(String name) can also update the Thread name.

Let’s see a sample code that shows how to give a name to the Thread using the Thread(String name) constructor, setName(String name) method and retrieve that name in the run() method using getName() method.

Sample code.

Sample output.

If you forget to provide any name while running the code, you’ll see the following output.

If you give a name to thread as “DemoThread” then the output will be. sleep(long milliseconds):

Suspends a thread for the specified period. If any other thread interrupts this sleeping thread, it will throw an InterruptedException. So it is suggested to enclose the sleep() method in the try block. Alternatively, the code’s method must include InterruptedException in its throws clause. boolean isAlive():

It determines if a thread is still running. JVM considers thread to be alive immediately before calling to thread’s run() method, during the execution of thread’s run() and immediately after return from run().

During that interval, the isAlive() method returns a Boolean true value. Otherwise, it returns false.

isAlive() method is useful in the situations when one thread needs to wait for another thread to finish its run() method.

Let’s see a sample code for sleep() and isAlive() method. join(long milliseconds):

This method gets called when a thread wants to wait for another thread to terminate. Let’s see a sample code for the <join()> method.

Let’s see a sample code for the <join()> method. Set Thread Types.

Threads fall under into following two categories.

  • User, and
  • daemon.

A user thread performs critical tasks that must finish before the application terminates. However, a daemon thread performs garbage collection and other background tasks. When an application’s starting thread (a user thread) ends, JVM checks whether any other user thread is running. If there is some running user thread, then JVM prevents the application from terminating. If there is no user thread running then JVM will terminate the application without bothering for the running daemon thread.

  • boolean isDaemon(): checks if the thread is a daemon thread.
  • setDaemon(boolean b): marks the thread as daemon or user thread. To start a daemon thread setDaemon(Boolean b) method must be called with argument “true.”
Let’s see a sample code for isDaemon() and setDaemon() method. Thread currentThread():

It returns the instance reference of the currently executing thread. Thread.State getState():

It returns the state of the thread.

Let’s see a sample code.

Sample output. yield():

This method causes the currently executing thread object to pause temporarily and allow other threads to run.

Let’s see a sample code.

The thread will halt after printing “In Run” due to the yield() method; since there is no other thread to execute so this thread will resume and print “Leaving run”. final int getPriority():

It returns the priority of the thread. final void setPriority(int priority):

This function is used to change the priority of a thread.

Let’s see a sample code. int getId():

It returns the id of the thread. interrupt():

It interrupts the thread. boolean isInterrupted():

tests if the thread has been interrupted and returns the interrupted flag either true or false. boolean interrupted():

The static interrupted() method tests if the thread has been interrupted.This method returns the interrupted flag after that it sets the flag to false if it is true.

Let’s see a sample code. suspend():

You can use it to suspend the thread. [deprecated] resume():

You can use it to resume the suspended thread. [deprecated] stop():

You can use it to halt the thread. [deprecated]


Note: Sun has deprecated a variety of Thread methods, such as suspend(), resume() and stop() because they can lock up your programs or damage objects. As a result, you should not call them in your code.


We’ve covered almost all the important areas of Java Thread class in the above section, hope it would help. In the next segment, you’ll see the two methods to create threads in Java.

1.4- Java Thread Creation Methods and Examples.

1.4.1- Java Multithreading (1) – Thread creation by Extending the Thread Class.

In this case, you need to complete the following steps to spawn a thread in a Java program.

  • Add a new class that extends the Thread class.
  • This newly created class should override the Run() method which is the entry point for the new thread.
  • Invokes the start() method to initiate the execution of the thread.

Let’s see a sample code as an example.


1.4.2- Java Multithreading (2) – Thread Creation by implementing the Runnable interface.

For this approach, you need to follow the below steps to create a thread.

  • Create a class that does the following.
    • Implements the Runnable interface.
    • Provides the implementation of the run() method.
  • The run() method is an entry point for the thread and it remains alive till the run() method finishes its execution.
  • Once you create the thread, bring it to the Running state by calling the start() method.
    • Note: The start() method calls the run() method implicitly.

Let’s see a sample code as an example.


1.4.3-Download Java multithreading code samples.

Now it’s time to download the sample projects so that you can easily understand the Java multithreading code snippets specified in this post. Please use the below link to start your download.

⇓ Download Multithreading Project.



If you don’t have Java SDK it on your system, please click here to download it. In case, you don’t already have Eclipse IDE then refer the link to get it now.


Final Thought.

We wish that the above Java multithreading tutorial would have helped you in walking a step further on the Java learning scale. In the next article of Java programming, we’ll give insights on different ways to implement synchronization in Java applications.

In case, this post was able to intrigue you then please share it with your friends or float on social media using the below share buttons.


All the very best,



  1. Virendra Thakur Reply

Leave a Reply