Answer» What is Multithreading? Multithreading is a Java feature that permits the execution of two or more portions of a program at the same time to maximise CPU efficiency. Each such portion of the program is referred to as a thread. Threads are lightweight processes within processes. Multitasking is accomplished through the use of multiprocessing and multithreading. Because threads share a memory, we employ multithreading rather than multiprocessing. They conserve memory by not allocating separate memory space, and context-switching between threads takes less time than processing.
The above image shows 3 processes wherein process 1 consists of 3 threads, process 2 consists of 2 threads and process 3 consists of 1 thread. Java Runnable Interface: In Java, java.lang.Runnable is an interface that a class must implement if its instances are to be executed by a thread. Java Thread Class: Thread programming is possible with Java’s Thread class. The Thread class contains constructors and methods for creating and operating on threads. Thread is a subclass of Object that implements the Runnable interface. Methods of the Java Thread Class: The following table shows the methods of the Java Thread class and its use cases.
| Method | Modifier and return type | Use Case |
|---|
| start() | void | start() is used to begin the thread’s execution. | | run() | void | It specifies the code to be executed by each thread. | | sleep() | static void | This function sleeps a thread for the period of time provided. | | currentThread() | static Thread | It returns a reference to the thread object that is presently running. | | join() | void | This function waits for a thread to terminate. | | getPriority() | int | This function returns the thread’s priority. | | getName() | String | getName() returns the thread’s name. | | setName() | void | setName() modifies the thread’s name. | | isAlive() | boolean | isAlive() is a boolean function that determines whether or not the thread is alive. | | getId() | long | This function returns the thread’s id. | | yield() | static void | This function causes the presently running thread object to pause and allow other threads to run for a short period of time. | | interrupt() | void | It interrupts the thread. | | suspend() | void | It is used to suspend the thread. | | destroy() | void | This function is used to destroy the thread group as well as all of its subgroups. | | stop() | void | This function is used to terminate the thread. | | resume() | void | resume() is a void function that is used to restart a suspended thread. | | isInterrupted() | boolean | isInterrupted() is a boolean function that determines whether or not the thread has been interrupted. | | setDaemon() | void | This function marks whether the thread is a daemon or a user thread. | | isDaemon() | boolean | This function determines whether the thread is a daemon thread. | | interrupted() | static boolean | This function checks if the current thread is interrupted. | | activeCount() | static int | This function returns the number of active threads in the thread group of the current thread. | | dumpStack() | static void | This function prints the current thread’s stack trace to the standard error stream. | | enumerate() | static int | This function copies the thread group and subgroups of all current threads into the provided array. | | holdLock() | static boolean | holdLock() is a static boolean function that returns true if and only if the current thread has the monitor lock on the provided object. | | checkAccess() | void | This function checks whether the currently running thread has the ability to change the thread. | | getStackTrace() | StackTraceElement[] | This method returns an array of stack trace items that describe the thread’s stack dump. | | getState() | Thread.State | getState() is used to return the thread’s current state. | | getThreadGroup() | ThreadGroup | getThreadGroup() returns the thread group that this thread belongs to. | | notifyAll() | void | This method is used to send a notification to all of an object’s waiting threads. | | notify() | void | This function is used to send a notification to only one thread that is waiting for an item. | | setContextClassLoader() | void | This method sets the Thread’s context ClassLoader. | | getContextClassLoader() | ClassLoader | getContextClassLoader() returns the thread’s context ClassLoader. | | toString() | String | Returns a string representation of this thread, containing its name, priority, and thread group. |
Java Multithreading has the following advantages:
- It does not impede the user because threads are independent and can conduct many operations at the same time.
- It saves time by allowing you to conduct multiple procedures at once.
- Because threads are self-contained, an exception in one thread has no impact on other threads.
How to implement multithreading in Java? Multithreading can be performed in Java using two different mechanisms:
- By Extending the Thread class.
- By implementing the Runnable Interface.
By extending the Thread class: We’ll make a class that extends the java.lang.Thread class. The run() method of the Thread class is overridden by this class. The run() procedure is where a thread starts its life. To begin thread execution, we construct an object of our new class and use the start() method. Start() calls the Thread object’s run() function. Example -
class Sample 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("An exception is caught"); } } }
class Multithread { public static void main(String[] args) { int n = 5; // Number of threads for (int i = 0; i < n; i++) { Sample obj = new Sample(); obj.start(); } } } Output -
Thread 20 is running Thread 18 is running Thread 21 is running Thread 19 is running Thread 17 is runningExplanation - In the above code, the Sample class extends the Thread class present in java.lang package. In the Multithread class, we create 5 threads by creating an instance of the Sample class. We then invoke the run() method of the instance created by calling the start() method of the instance. By implementing the Runnable Interface: We make a new class that implements the java.lang.Runnable interface and overrides the run() method. After that, we create a Thread object and call its start() method. Example -
class Sample implements Runnable { 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("An exception is caught"); } } }
class Multithread { public static void main(String[] args) { int n = 5; // Number of threads for (int i = 0; i < n; i++) { Thread obj = new Thread(new Sample()); obj.start(); } } } Output -
Thread 20 is running Thread 18 is running Thread 21 is running Thread 19 is running Thread 17 is runningExplanation: In the above code, the class Sample implements the Runnable interface. In the sample class, we override the run() method. In the Multithread class, we create 5 threads by creating an instance of the Thread class. Runnable Interface vs. Thread Class: The following are the key differences between using the Runnable interface and the Thread class:
- Because Java doesn’t support multiple inheritances, if we extend the Thread class, we won’t be able to extend any other classes. Our class, however, can still extend other base classes if we implement the Runnable interface.
- We can obtain rudimentary thread functionality by extending the Thread class, which has several built-in methods like yield() and interrupt() that aren’t available in the Runnable interface.
- When you use runnable, you’ll get an object that can be shared by numerous threads.
Additional Resources:
- https://www.interviewbit.com/blog/java-developer-skills/
- https://www.interviewbit.com/blog/java-projects/
- https://www.interviewbit.com/blog/java-frameworks/
- https://www.interviewbit.com/java-mcq/
- https://www.interviewbit.com/blog/java-11-features/
- https://www.interviewbit.com/blog/java-8-features/
- https://www.interviewbit.com/blog/java-books/
- https://www.interviewbit.com/blog/java-developer-resume/
- https://www.interviewbit.com/blog/top-java-applications/
- https://www.interviewbit.com/blog/characteristics-of-java/
|