Multithreading in java| All about java multi-threading

Multithreading in java| All about java multi-threading

Multithreading in java:-

This is a Java feature that allows the execution of more than one thread at the same time to maximize CPU utilization. Each thread is referred to as a thread. A thread is a very lightweight process within process.

Threads can be created by using two ways :

  • By Thread class
  • By Implementing the Runnable Interface

Multithreading vs Multiprocessing

Creating a multithreaded application regardless of whether the machine has two cores or sixteen is what we mean by multithreading. The OS handles allocation and execution.


Thread Life Cycle in Java:-

There are various stages of the life cycle of the thread as shown in the above diagram:-

1. New: As long as the program does not start the thread, the thread is considered as a born thread. It is created with the class "Thread".
2. Runnable: This page starts the thread by invoking the start method. Thread control is then passed to the scheduler to complete the execution. The scheduler decides whether the thread should run or not.
3. Running: In addition, the thread's state changes to "running" when it starts executing. The scheduler picks one thread from the thread pool, which executes in the application.
4. Waiting: A thread in a waiting state has to wait for another thread to complete execution because there are multiple threads running throughout the application. Therefore, one thread has to wait, until the other thread executes. Therefore, this condition is called a waiting state.
5. Dead: After the thread has completed processing, it is placed in a "dead state". It has been in a running state before it completed processing.

What is Thread Priority?

A thread can be assigned a priority when it is created. Changing the priority of a thread does not guarantee that it will execute before a lower priority thread. Whenever a thread is launched, its execution is handled by Thread Scheduler, and the JVM is not responsible for running it. The Thread Scheduler is part of the implementation of the Operating System.

How Do We Create Thread in Java?

The Runnable interface can be implemented or Thread Classes can be extended to create Threads.

Thread t = new Thread(new Runnable(){
@Override
public void run() {
}
});

To start a new thread, enter the one-line statement shown above. We are creating an anonymous class here called Runnable. You can create a Thread with less code if you are familiar with lambda expressions.

Runnable runnable = () -> System.out.println("Hello by Multi-threading");

We must call the start() method on a Thread after we have created one.

runnable.start();


Creating Thread using Thread class:-

Override the run() method in the Thread class with a class that extends the java.lang.Thread class. In the run() method of the Thread object, we start a thread by creating an object of our class and calling start(). Finally, run() invokes the thread.

// 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 Main{ 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(); } } }

Output:-

Thread 14 is running

Thread 16 is running

Thread 12 is running

Thread 15 is running


Creating thread using runnable interface:-

Then we instantiate a Thread object and call the start() method on this object. Finally, we wrap everything up in a new class that implements java.lang.Runnable interface.

// Java code for thread creation by implementing // the Runnable Interface class MultithreadingDemo 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("Exception is caught"); } } } // Main Class class Main { public static void main(String[] args) { int n = 8; // Number of threads for (int i = 0; i < n; i++) { Thread object = new Thread(new MultithreadingDemo()); object.start(); } } }


Output:-

Thread 12 is running

Thread 15 is running

Thread 14 is running

Thread 11 is running


Thread Class vs Runnable Interface

  • Because Java does not support multiple inheritances, extending the Thread class makes our classes ineligible to extend other classes. However, if our class implements the Runnable interface, it can extend other base classes.
  • By extending the Thread class, we can get basic thread functionality because it offers some inbuilt methods like yield(), interrupt(), and so forth that runnable does not.
  • You will be able to share an object amongst multiple threads when using runnable.

Post a Comment

0 Comments