13
SepUnderstanding Multithreading in Java with Examples
Multithreading in Java
Do you know that you can execute more than one thread at once in Java? Multithreading in Java! This is the process used. Execution of two or more threads at the same time within a single program is allowed by Multithreading in Java.
We will try to understand in detail what Java Multithreading is in this Java Tutorial. We will also go through other concepts related to it. To learn more about various concepts of Java Programming, enroll in a Java Certification Training Program.
Read More: Best Java Developer Roadmap 2024 |
Before digging deep into multithreading, it would be good to know about threads and learn about multitasking.
What is Multitasking?
A computer's capacity to implement several tasks at the same time is referred to as multitasking. Broadly speaking, it comes in two varieties which are process-oriented or Multiprocessing and thread-oriented or Multithreading.
Types of Multitasking
1. Multiprocessing in Java
Multiprocessing means that a system has a capacity that exceeds a processor as well as can also execute various processes at the same time. In Java, this is done by creating several parallel running processes. Each process is executed in its own JVM instance.
2. Multithreading in Java
With Java's multithreading, programs may have multiple threads running concurrently. Threads share the same memory space and can access the same resources; this is more efficient than process-based multitasking.
What is a Thread in Java?
In Java, there is a concept of a thread which means a lightweight process with its own call stack. However, it can possibly share the same resources and data with other threads. In Java, multithreading is supported natively so you just simply have to build synchronized applications.
Example of Threads in Java:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running.");
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
Hereby, it is explained that a `MyThread` thread instance is created using an extended `Thread` class. The 'run' method is called once the thread has started running by invoking the 'start' method.
Output
Thread is running.
Lifecycle of a Thread in Java
A thread in Java goes through several states during its lifecycle. These states are as follows:
1. New
Whenever a thread is made, it stays in the "new" condition; in this condition, the thread isn’t qualified to run yet.
2. Runnable
When a thread object's start() method is called, the thread will start to be scheduled for running. It is ready to run and waiting for the operating system to allocate CPU time.
3. Running
When the thread scheduler picks a thread from the runnable pool, it enters the "running" state and executes its task.
4. Waiting
If it wants another thread to do something particular, a thread goes into the "waiting" state. This can occur through various mechanisms, such as wait(), sleep(), or waiting for I/O operations.
5. Dead
The run method completion or an exception being thrown brings the thread into the "dead" state. After entering this state, the thread cannot be restarted.
Read More: Java Multithreading Interview Questions and Answers 2024 |
Now that we have covered the important requirements the main topic is going to be Multithreading in Java.
What is Multithreading in Java?
Multithreading in Java is the execution of multiple threads within a single application at the same time. Each thread runs in parallel, performing different tasks. This capability is essential for developing high-performance applications, such as servers, which need to handle multiple client requests simultaneously.
Methods of Multithreading in Java
Java provides several methods to implement multithreading, including:
- Extending the Thread Class- Make a class that extends Thread and overrides its run method.
- Implement the Runnable Interface - Implement the Runnable interface and pass the instance to a Thread object.
Example of Multithreading in Java:
class MyThread extends Thread {
private String threadName;
MyThread(String name) {
threadName = name;
}
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(threadName + " is running: iteration " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
System.out.println(threadName + " has finished running.");
}
public static void main(String[] args) {
MyThread t1 = new MyThread("Thread 1");
MyThread t2 = new MyThread("Thread 2");
t1.start(); // Start Thread 1
t2.start(); // Start Thread 2
}
}
When the 'run' method of each thread is running at the same time, many threads execute at once.
Output
Thread 1 is running: iteration 1
Thread 2 is running: iteration 1
Thread 1 is running: iteration 2
Thread 2 is running: iteration 2
Thread 1 is running: iteration 3
Thread 2 is running: iteration 3
Thread 1 has finished running.
Thread 2 has finished running.
Multiprocessing vs. Multithreading in Java
Feature | Multiprocessing | Multithreading |
Definition | Involves multiple processes running on different processors or cores. | Involves multiple threads running within a single process. |
Memory Space | Each process has its own memory space. | Threads share the same memory space and resources. |
Isolation | High isolation between tasks; processes do not share memory. | Lower isolation; threads share memory, making communication easier. |
Suitability | Suitable for applications requiring high isolation between tasks. | Suitable for applications needing concurrent tasks within the same application. |
Performance | Can leverage multiple processors or cores effectively. | Can leverage multi-core processors but within a single process. |
Advantages of Multithreading in Java
- Resource Sharing-Threads share the same memory and resources, making it efficient.
- Responsiveness-Multithreading can make applications more responsive by performing background operations.
- Scalability- Utilizing multiple threads can improve the performance of applications on multi-core processors.
- Simplified Modeling-Suitable for applications that require multiple concurrent activities.
Drawbacks of Multithreading in Java
- When writing multi-thread programs, we always strive hard to avoid complexities liable to give rise to pitfalls such as deadlocks or even race conditions.
- Debugging multithreaded applications is more challenging as compared to the single-threaded ones.
- Context switching between threads can introduce overhead and affect performance.
Conclusion
FAQs
Q1. What is multithreading and its benefits?
Q2. What is multithreading types?
- User-Level Threads
- Kernel-Level Threads