Java Multithreading
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
- Extending the Thread class
- Implementing the Runnable Interface
Example: – Thread creation by extending the Thread class
To create a new thread in Java, we can extend the java.lang.Thread class and override its run() method. This is where the thread’s execution starts. Then, we can create an instance of our class and call the start() method to begin the execution of the thread. The start() method will then call the run() method of the Thread object.
Java
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 17 is running Thread 14 is running Thread 12 is running Thread 13 is running Thread 18 is running Thread 11 is running Thread 16 is running
Java Cheat Sheet
Java is a programming language and platform that has been widely used since its development by James Gosling in 1982. It follows the Object-oriented Programming concept and can run programs written in any programming language. Java is a high-level, object-oriented, secure, robust, platform-independent, multithreaded, and portable programming language All those words are collectively called Java Buzzwords. It is commonly used for programming web-based, window, enterprise, and mobile applications. This Java Cheat Sheet article has been written by experts in Java and based on the experience of students who have recently undergone Java interviews.
This Core Java Cheat Sheet has been designed by Java experts, based on the experience of students who have recently undergone Java interviews. Whether you are a beginner or an experienced Java developer, this Java Cheat Sheet is a valuable resource for quickly accessing essential syntax, concepts, and best practices related to Java Programming.