Introduction
The process of executing multiple threads concurrently is called Multithreading in Java. This article will explain Multithreading and how Multithreading works in Java with code examples. In Java, threads use a shared memory location.
What is Thread in Java?
A thread is a lightweight small process or the smallest unit of the processing, which can run concurrently with the other threads of the same process.
Threads are independent because they all have a separate path of execution due to which if an exception occurs in one thread, it doesn't affect the execution of other threads. All the threads of a process share a common memory area. The process of executing multiple threads is called Multithreading in Java.
Let's understand the figure, given below.
In the figure, a thread is executed inside the process, and the context-switching between the threads. Here the multiple processes in the OS and the single process can have multiple threads but only one thread executed at a time.
Multithreading is a procedure of executing multiple threads at the same time. Multiprocessing and Multithreading are used to achieve multitasking in Java. Saving memory and context-switching between the threads takes less time than the process. Multithreading is mainly used in games, animation, etc.
What are the Advantages of Multithreading in Java?
- The threads are independent due to which we can perform multiple operations at the same time.
- We can perform many operations simultaneously, so it saves time.
- The Threads don't affect other threads if an exception occurs in a single thread.
- Better use of CPU resources.
- Decrease the cost of maintenance.
- Better use of cache storage by utilization of resources.
What are the Disadvantages of Multithreading in Java?
- Multiple threads can interfere with each other when sharing hardware resources such as caches or transaction look-aside buffers(TLBs).
- The execution time of a single thread can be degraded, even when only one thread is executing.
- Complex debugging and testing process.
- Unpredictable results.
Why do we use Multithreading in Java?
We use Multithreading in Java for achieving Multitasking.
What is Multitasking in Java?
Multitasking is the process of executing multiple tasks at the same time. We use multitasking to utilize the CPU.
Multitasking can be achieved in two ways. Which are
Process-based Multitasking
Process-based multitasking means Multiprocessing, in this, every process has its own memory address and every process allocates a separate memory area.
The process is heavy-weight. The cost of communication during the process is very high. Switching from one process to another process requires some time to save and load the registers, memory maps, updates, lists, etc.
Thread-based Multitasking
Thread-based multitasking means Multithreading. in which all the threads share the same address space.
The thread is lightweight. The cost of communication between the threads is very low. At least one process is required for each thread.
What is thread life-cycle in Java?
A thread goes through many different stages in its life cycle. For example, a thread is born, the thread starts, the thread runs, and then the thread dies. The life cycle of the thread is controlled by JVM in Java. For a better understanding of the thread, we explain it in the five states.

New
A new state is the first state of the thread. The thread is in the new state if we create an object of the Thread class but before the invocation of the start() method.
Runnable
After a new thread starts, the thread is in the second state after the invocation of the start() method, but the scheduler has not selected it to be in the running thread.
Running
The third state is running. The thread is in a running state if the thread scheduler has selected it.
Non-Runnable (Blocked)
The fourth state is non-runnable(blocked). This is the state when the thread is alive but is currently not eligible to run.
Terminated
The last state of a thread is terminated. A thread is in the terminated state when its run() method exits.
How threads are created in Java?
Threads are created in Java in two ways, first by extending the Thread class and second by implementing the Runnable interface by any Java class.
How many ways create a thread in Java?
There are two ways to create a thread in Java multithreading.
- By Extending the Thread class
- By implementing the Runnable method
What is the Thread class in Multithreading?
Thread class provides many constructors and methods to create and perform many operations on a thread. Thread class extends an Objects class and implements a Runnable interface in Java multithreading.
Constructors of Thread class
1. Thread()
Allocates a new Thread object. The complete program is listed below.
public class ThreadConstructor extends Thread {
public void run() {
System.out.println("This is example of Thread Constructor");
}
public static void main(String args[]) {
ThreadConstructor t = new ThreadConstructor();
t.start();
}
}
The output of the following code generates the following output.

2. Thread(String name)
Allocates a new Thread object. The complete program is listed below.
public class ThreadConstructor1 extends Thread{
String tname;
ThreadConstructor1(String tname) {
this.tname = tname;
}
public void run() {
System.out.println(tname);
}
public static void main(String args[]) {
ThreadConstructor1 t = new ThreadConstructor1("First Thread");
t.start();
}
}
The output of the following code generates the following output.

3. Thread(Runnable r)
Allocates a new Thread object. The complete program is listed below.
public class ThreadConstructor2 implements Runnable {
public void run() {
System.out.println("This is the example of Thread(Runnable target) constructor");
}
public static void main(String args[]) {
ThreadConstructor2 s = new ThreadConstructor2();
Thread t = new Thread(s);
t.start();
}
}
The output of the following code generates the following output.

4. Thread(Runnable r, String name)
Allocates a new Thread object. The complete program is listed below.
public class ThreadConstructor3 implements Runnable {
ThreadConstructor3() {
}
public void run() {
System.out.println("This is the example of Thread(Runnable target, String name) constructor");
}
public static void main(String args[]) {
ThreadConstructor3 s = new ThreadConstructor3();
Thread t = new Thread(s, "CsharpCorner");
t.start();
}
}
The output of the following code generates the following output.

Methods of the Thread class in Java
1. public void run()
This method is used to perform an action for a thread. The complete program is listed below.
public class ThreadRunMethod extends Thread {
public void run() {
System.out.println("This is the example of run() method");
}
public static void main(String args[]) {
ThreadRunMethod t = new ThreadRunMethod();
t.start();
}
}
The output of the following code generates the following output.

2. public void Thread.start()
This method is used to start the execution of the thread. JVM calls the run() method to start the thread. The complete program is listed below.
public class ThreadStartMethod extends Thread {
public void run() {
System.out.println("This is the example of start() method");
}
public static void main(String args[]) {
ThreadStartMethod s = new ThreadStartMethod();
s.start();
}
}
The output of the following code generates the following output.

3. public void Thread.sleep(long milliseconds)
The Thread class sleep() method is used to sleep a thread for a particular duration of time. If one thread sleeps for the specified time then the thread scheduler picks up other threads and so on. The complete program is listed below.
public class ThreadSleepMethod extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[]) {
ThreadSleepMethod t1 = new ThreadSleepMethod();
ThreadSleepMethod t2 = new ThreadSleepMethod();
t1.start();
t2.start();
}
}
The output of the following code generates the following output.

4. public void Thread.join()
The join method is used to wait for a thread to die. The complete program is listed below.
public class ThreadJoinMethod1 extends Thread {
public void run() {
for (int i = 0; i <= 3; i++) {
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[]) {
ThreadJoinMethod1 t1 = new ThreadJoinMethod1();
ThreadJoinMethod1 t2 = new ThreadJoinMethod1();
ThreadJoinMethod1 t3 = new ThreadJoinMethod1();
t1.start();
try {
t1.join();
} catch (Exception e) {
System.out.println(e);
}
t2.start();
t3.start();
System.out.println("This is Thread join() method example");
}
}
The output of the following code is listed below.

5. public void Thread.join(long milliseconds)
This method is used to wait for a thread to die for a specified millisecond. The complete program is listed below.
public class ThreadJoinMethod2 extends Thread {
public void run() {
for (int i = 0; i <= 3; i++) {
try {
Thread.sleep(700);
} catch (Exception e) {
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[]) {
ThreadJoinMethod2 t1 = new ThreadJoinMethod2();
ThreadJoinMethod2 t2 = new ThreadJoinMethod2();
ThreadJoinMethod2 t3 = new ThreadJoinMethod2();
t1.start();
try {
t1.join(1000);
} catch (Exception e) {
System.out.println(e);
}
t2.start();
t3.start();
System.out.println("This is Thread join() method example");
}
}
The output of the following code generated the following output.

6. public void Thread.currentThread()
The thread class static method currentThread() returns the reference of the Thread object that calls this method. The complete program is listed below.
public class ThreadCurrentMethod extends Thread {
@Override
public void run() {
Thread t = Thread.currentThread();
String threadName = t.getName();
System.out.println("Inside run() method: " + threadName);
}
public static void main(String[] args) {
ThreadCurrentMethod ct = new ThreadCurrentMethod ();
ct.start();
Thread t = Thread.currentThread();
String threadName = t.getName();
System.out.println("Inside main() method: " + threadName);
}
}
The output of the following code generates the following output.

7. public String Thread.getName()
This method is used to return the name of the thread. The complete program is listed below.
public class ThreadGetnameMethod extends Thread {
public void run() {
System.out.println("threads running fast...");
}
public static void main(String args[]) {
ThreadGetnameMethod t1 = new ThreadGetnameMethod();
System.out.println("Name of thread 1:" + t1.getName());
t1.start();
}
}
The output of the following code generates the following output.

8. public String Thread.setName(String name)
This method is used to change the name of the thread. The complete program is listed below.
public class ThreadSetnameMethod extends Thread {
public void run() {
System.out.println("threads running fast...");
}
public static void main(String args[]) {
ThreadSetnameMethod t1 = new ThreadSetnameMethod();
System.out.println("Name of thread 1: " + t1.getName());
t1.start();
t1.setName("Strong Thread");
System.out.println("After changing name of thread 1:" + t1.getName());
}
}
The output of the code generates the following output.

9. public int Thread.currentThread().getPriority()
This method is used to return the priority of the thread. The complete program is listed below.
public class ThreadGetPriorityMethod extends Thread {
public void run() {
System.out.println("Current thread priority is:" + Thread.currentThread().getPriority());
}
public static void main(String args[]) {
ThreadGetPriorityMethod g = new ThreadGetPriorityMethod();
g.start();
}
}
The output of the following code generates the following output.

10. public void Thread.currentThread().setPriority(int priority)
This method is used to change the priority of the thread. The complete program is listed below.
public class ThreadSetPriorityMethiod extends Thread {
public void run() {
System.out.println("Current thread priority is:" + Thread.currentThread().getPriority());
}
public static void main(String args[]) {
ThreadSetPriorityMethiod s = new ThreadSetPriorityMethiod();
s.setPriority(8);
s.start();
}
}
The output of the following code generates the following output.

What is the Runnable interface in Java?
The runnable interface must be implemented by any class, whose instances are intended to be executed by a thread. The Runnable interface has only one run() method.
public void run()
This method is used to perform an action for a thread. The complete program is listed below.
public class RunnableRunMethod implements Runnable {
@Override
public void run() {
System.out.println("This is the example of Runnable interface run() method");
}
public static void main(String[] args) {
RunnableRunMethod m = new RunnableRunMethod();
Thread t = new Thread(m);
t.start();
}
}
The output of the following code generates the following output.
How to start a thread in Java?
start() method is used to start a newly created thread. It performs may tasks, Which are-
- A new thread start.
- The thread shifts from the new state to the runnable state.
- If the thread gets a chance to execute, its target run() method will run.
The complete program is listed below.
public class ThreadExample extends Thread {
public void run() {
System.out.println("This is example of how to start a Thread in Java.");
}
public static void main(String args[]) {
ThreadExample t = new ThreadExample();
t.start();
}
}
The output of the following code generates the following output.
Can We start a thread twice in Java?
No, we cannot start a thread twice, after starting a thread, it can never be started again. If we do then all IllegalThreadStateException is thrown. In this case, the thread will run once but next time, it will throw an exception. The complete program is listed below.
public class StartThreadTwice extends Thread {
public void run() {
System.out.println("we can not start a thread twice in a program");
}
public static void main(String args[]) {
ThreadExample t1 = new ThreadExample();
t1.start();
t1.start(); // Exception
}
}
The output of the following code generates the following output.

What is the Thread scheduler in Java?
The thread scheduler is part of JVM, which decides which thread should run. There is no assurance that which runnable thread will be chosen to run by the scheduler. Any thread in the runnable state can be chosen by the scheduler to be the one and only running thread and if a thread is not in a runnable state, then it cannot be chosen to be the currently running thread. Some methods can influence the scheduler to some extent and we can't control the behavior of the thread scheduler. Only one thread at a time can run in a single process in Java.
The thread scheduler generally uses preemptive scheduling or time-slicing scheduling to schedule the threads in Java.











Aman GuptaPosted Aug 7, 2021, 3:59 PM
Very Well Written Article. Thanks, Vijay Kumari.
Rajanikant HawaldarPosted Sep 8, 2019, 12:28 PM
nice article