Multithreading in Java
Multithreading in Java
Multithreading in Java refers to the concurrent execution of multiple threads, which are lightweight sub-processes and the smallest units of processing.
In the context of multitasking, both multiprocessing and multithreading are used, but multithreading is preferred because it enables threads to share a common memory space.
This shared memory approach conserves memory compared to multiprocessing, where each process has its own memory allocation. Additionally, context-switching between threads is more efficient and faster compared to switching between processes.
Java's multithreading capabilities find extensive use in applications such as games and animations, where concurrent execution of tasks is crucial for achieving responsive and interactive user experiences.
Advantages
Multithreading doesn't hinder user interaction since threads operate independently, enabling multiple operations to occur simultaneously without blocking the user.
The ability to carry out multiple operations concurrently results in time efficiency and time savings.
Threads work in isolation from one another, which means that if an exception occurs within one thread, it won't impact other threads.
Creating a thread by extending the Thread class involves the following steps:
We define a new class that inherits from the java.lang.Thread class.
Within this class, we override the run() method, which is a key method provided by the Thread class. This run() method serves as the entry point for the thread's activities.
To initiate the execution of a thread, we create an instance of our new class.
We then call the start() method on this object. The start() method, in turn, triggers the execution of the run() method within the thread.
// Java code for thread creation by extending
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println( "Thread " + Thread.currentThread().getId() + " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
public class Multithread {
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Output:-
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running