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.
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.
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.
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();
}
}
}
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:
Note: also read about the Interface vs Abstract class
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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…