In Java, a thread is a small part of a program that can be executed independently. It allows concurrent execution of multiple tasks or processes, enabling programs to perform multiple operations simultaneously. Parallelism can be achieved and system resources, like CPU cores, can be used to the fullest extent possible thanks to threads.
The Thread class, which is a component of the java.lang package, is used to represent threads in Java. By creating and managing threads, developers can execute different sections of code concurrently, leading to improved performance and responsiveness in multi-tasking scenarios.
A class that extends java.lang is created. thread type. The run() method of the Thread class is overridden by this class. A thread is created inside the run() method. In order 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.
class Multithreadings extends Thread { public void run(){ try { System.out.println("Thread " + Thread.currentThread().getId()+ "running"); } catch (Exception e) { System.out.println("Exception caught"); } } } public class Main { // class to use user define above exception public static void main(String args[]){ int th = 5; // Number of threads for (int i = 0; i < th; i++) { Multithreadings object= new Multithreadings(); object.start(); } } }
Output:
Thread 17 running
Thread 14 running
Thread 18 running
Thread 15 running
Thread 16 running
We develop a brand-new class that complies with Java.lang. run() method is overridden by the runnable interface. After that, we create a Thread object and call its start() method.
class Multithreadings implements Runnable { public void run(){ try { System.out.println("Thread " + Thread.currentThread().getId()+ " running"); } catch (Exception e) { System.out.println("Exception caught"); } } } public class Main { // class to use user define above exception public static void main(String args[]){ int th = 5; // Number of threads for (int i = 0; i < th; i++) { Thread thread= new Thread(new Multithreadings()); thread.start(); } } }
Output:
Thread 14 running
Thread 18 running
Thread 17 running
Thread 16 running
Thread 15 running
Police Colony
Patna, Bihar
India
Email:
Post your comment