1.

Java Multithreading

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.

MethodModifier and return typeUse Case
start()voidstart() is used to begin the thread’s execution.
run()voidIt specifies the code to be executed by each thread.
sleep()static voidThis function sleeps a thread for the period of time provided.
currentThread()static ThreadIt returns a reference to the thread object that is presently running.
join()voidThis function waits for a thread to terminate.
getPriority()intThis function returns the thread’s priority.
getName()StringgetName() returns the thread’s name.
setName()voidsetName() modifies the thread’s name.
isAlive()booleanisAlive() is a boolean function that determines whether or not the thread is alive.
getId()longThis function returns the thread’s id.
yield()static voidThis function causes the presently running thread object to pause and allow other threads to run for a short period of time.
interrupt()voidIt interrupts the thread.
suspend()voidIt is used to suspend the thread.
destroy()voidThis function is used to destroy the thread group as well as all of its subgroups.
stop()voidThis function is used to terminate the thread.
resume()voidresume() is a void function that is used to restart a suspended thread.
isInterrupted()booleanisInterrupted() is a boolean function that determines whether or not the thread has been interrupted.
setDaemon()voidThis function marks whether the thread is a daemon or a user thread.
isDaemon()booleanThis function determines whether the thread is a daemon thread.
interrupted()static booleanThis function checks if the current thread is interrupted.
activeCount()static intThis function returns the number of active threads in the thread group of the current thread.
dumpStack()static voidThis function prints the current thread’s stack trace to the standard error stream.
enumerate()static intThis function copies the thread group and subgroups of all current threads into the provided array.
holdLock()static booleanholdLock() is a static boolean function that returns true if and only if the current thread has the monitor lock on the provided object.
checkAccess()voidThis 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.StategetState() is used to return the thread’s current state.
getThreadGroup()ThreadGroupgetThreadGroup() returns the thread group that this thread belongs to.
notifyAll()voidThis method is used to send a notification to all of an object’s waiting threads.
notify()voidThis function is used to send a notification to only one thread that is waiting for an item.
setContextClassLoader()voidThis method sets the Thread’s context ClassLoader.
getContextClassLoader()ClassLoadergetContextClassLoader() returns the thread’s context ClassLoader.
toString()StringReturns a string representation of this thread, containing its name, priority, and thread group.

Java Multithreading has the following advantages:


  1. It does not impede the user because threads are independent and can conduct many operations at the same time.

  2. It saves time by allowing you to conduct multiple procedures at once.

  3. 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 running

Explanation - 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 running

Explanation: 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:


  1. 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.

  2. 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.

  3. When you use runnable, you’ll get an object that can be shared by numerous threads.

Additional Resources:

  1. https://www.interviewbit.com/blog/java-developer-skills/

  2. https://www.interviewbit.com/blog/java-projects/

  3. https://www.interviewbit.com/blog/java-frameworks/

  4. https://www.interviewbit.com/java-mcq/

  5. https://www.interviewbit.com/blog/java-11-features/

  6. https://www.interviewbit.com/blog/java-8-features/

  7. https://www.interviewbit.com/blog/java-books/

  8. https://www.interviewbit.com/blog/java-developer-resume/

  9. https://www.interviewbit.com/blog/top-java-applications/

  10. https://www.interviewbit.com/blog/characteristics-of-java/




Discussion

No Comment Found