Java’s multithreading feature enables the concurrent execution of two or more program components for maximum CPU efficiency. A thread refers to each component of such a program. Thus, threads are quick processes contained within a process.
Java multithreading has a few benefits.
- Because threads are independent, and you can run several operations simultaneously, the user is not blocked.
- It saves time because multiple operations can be completed simultaneously.
- Because each thread is independent, if an exception arises in one thread, it does not affect the other threads.
Multitasking
The ability to run multiple programs (or processes) simultaneously on a single CPU is known as multitasking. This is achieved by rapidly switching between different programs so that it appears as though all of them are running at once.
Thread in Java
The smallest unit of processing is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread, it does not affect the others. It makes use of shared memory.
Thread creation by extending the Thread class:
We create a class that extends the java.lang.Thread class. This class overrides the run() method of the Thread class. A thread is created inside the run() method. To initiate the execution of a thread, we create an object of our new class and call the start() method. Start() calls the Thread object’s run() method.
// Java code for thread creation by extending
// the Thread class
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
Some Java Thread Methods:
- void start(): It begins the thread’s execution.
- void run(): It is employed to carry out a thread’s action.
- static void sleep(): It sleeps a thread for the specified amount of time.
- static Thread currentThread(): It gives back a pointer to the thread object that is currently running.
Note: also read about the Interface vs Abstract class
Follow Me
If you like my post, please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment