Java Multithreading – Learn Everything That You Should Know

Greetings friends, in this post we are going to explain Java multithreading, its pros, and cons, and the thread lifecycle. Next, you’ll get to see the details of thread class and its methods. Finally, learn how to create threads using thread class and runnable interface.

Also, we’ve supplemented the thread concepts with the help of state of the art examples and code samples. Now, before moving forward, let’s learn the basic meaning of a process and thread.

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.

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.

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

Java Multithreading – Everything You Should Know.

What is multithreading in Java?

  • Java multithreading enables the execution of multiple threads simultaneously.
  • It allows 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

What are Pros and Cons 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.


  • 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.

What is Thread Lifecycle in Java?

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 remains 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.

How to create 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.

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.

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.

General methods to manage the Threads.


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


This method is the 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 a 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 an 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.


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.


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.


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


You can use it to resume the suspended thread. [deprecated]


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.

Java Thread Creation Methods and Examples.

Create thread 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.


 Create thread 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.


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.

Summary – Java Multithreading.

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 icons.




  1. Virendra Thakur Reply
    • Harsh S. Reply

Leave a Reply