Multithreading concept in Java

 

Introduction

Multithreading is a Java feature that enables for the parallel execution of two or more portions of a programme in order to maximise CPU efficiency. Each component of such a software is referred to as a thread. Threads are therefore lightweight processes within processes. Threads can be generated by two mechanisms: Thread class extension.

In Java, both multithreading and multiprocessing are utilised for multitasking, although we favour multithreading. This is because the threads share a memory space, which saves memory, and the content-switching between the threads is a little faster than the process.

Few more advantages of Multithreading are:

• Multithreading saves time because it allows you to execute numerous actions at the same time. 

• Because the threads are independent, it does not prevent the user from performing multiple operations at the same time, and if an error occurs in one thread, it does not effect other threads.


What exactly are Threads in Java?

A thread is a relatively light procedure. Unlike many other programming languages, Java has built-in support for multithreading. A multithreaded programme has two or more components that can execute at the same time. Each component of such a programme is referred to as a thread, and each thread defines a distinct route of execution. Thus, multithreading is a subset of multitasking.

The Java Thread Model-Why use Threads in Java?

The Java run-time system depends on threads for many things. Threads reduce inefficiency by preventing the waste of CPU cycles.

Threads exist in several states. Following are those states:  

1.     New

2.     Runnable

3.     Running

4.     Non-Runnable (Blocked)

         5.   Terminated  


New

A new thread begins its life cycle in this condition.. This is also called a born thread. The thread is in the new state if you create an instance of Thread class but before the invocation of the start() method

Runnable

After a newly born thread is initiated, it becomes runnable. A thread would be executing its task in this situation.

 Running

When the thread scheduler selects the thread then, that thread would be in a running state.

Non-Runnable (Blocked)                                   

In this state, the thread is still alive, but it is temporarily ineligible to operate

Terminated                                           

A thread is terminated due to the following reasons:

·        Either its run() method exists normally, i.e., the thread’s code has executed the program.

·        Or due to some unusual errors like segmentation fault or an unhandled exception.

           A thread that has been terminated does not consume any CPU cycles

                


Multithreading in Java 

Thread Class and Runnable Interface

Java's multithreading system is based on the Thread class, its methods, and the Runnable interface. Your application will either extend Thread or implement the Runnable interface to establish a new thread.The Thread class defines several methods that help manage threads.The table below displays the same:


Main Java Thread

Why is Main Thread so important?

  •       This thread has an impact on the other 'child' threads.
  •        Because it performs various shutdown actions
  •        When you start your software, it creates it automatically


How to Create a Java Thread? 

                      

·        By implementing the Runnable interface.

·        By extending the Thread


Runnable Interface

The easiest way to create a thread is to create a class that implements the Runnable interface.

To implement Runnable interface, a class need only implement a single method called run( ), which is declared like this:

public void run( )

Inside run( ), we will define the code that constitutes the new thread.

Example:

public class MyClass implements Runnable {

public void run(){

System.out.println("MyClass running");

   }

}

To execute the run() method by a thread, pass an instance of MyClass to a Thread in its constructor(constructor in Java is a block of code similar to a method that’s called when an instance of an object is created). Here is how that is done.

Thread t1 = new Thread(new MyClass ());

t1.start();

When the thread is started it will call the run() method of the MyClass instance instead of executing its own run() method. The above example would print out the text “MyClass running“.


Extending Java Thread

The second technique is to build a new class that extends Thread, override the run() function, and then create an instance of that class. After you call start, the thread will perform the run() function (). Here's an example of a Java Thread subclass.

public class MyClass extends Thread {

     public void run(){

     System.out.println("MyClass running");

   }

}

To create and start the above thread you can do like this.

MyClass t1 = new MyClass ();

T1.start();

When the run() method executes it will print out the text “MyClass running“.

So far, we have been using only two threads: the main thread and one child thread. However, our program can affect as many threads as it needs. Let’s see how we can create multiple threads.

 

Creating Multiple Threads

class MyThread implements Runnable {

String name;

Thread t;

    MyThread (String thread){

    name = threadname;

    t = new Thread(this, name);

System.out.println("New thread: " + t);

t.start();

}

 

 

public void run() {

 try {

     for(int i = 5; i > 0; i--) {

     System.out.println(name + ": " + i);

      Thread.sleep(1000);

}

}catch (InterruptedException e) {

     System.out.println(name + "Interrupted");

}

     System.out.println(name + " exiting.");

}

}

 

class MultiThread {

public static void main(String args[]) {

     new MyThread("One");

     new MyThread("Two");

     new NewThread("Three");

try {

     Thread.sleep(10000);

} catch (InterruptedException e) {

      System.out.println("Main thread Interrupted");

}

      System.out.println("Main thread exiting.");

      }

}

 

The output from this program is shown here:

 

New thread: Thread[One,5,main]

 New thread: Thread[Two,5,main]

 New thread: Thread[Three,5,main]

 One: 5

 Two: 5

 Three: 5

 One: 4

 Two: 4

 Three: 4

 One: 3

 Three: 3

 Two: 3

 One: 2

 Three: 2

 Two: 2




Blog by student of vishwakarma institute of technology, deparment of department of multidisciplinary engineering.

Shubham Ghadge 

Rushikesh Gholap

Faizaan Khan 

Arjun Lande 

Vishal Malame 

                 

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. Very informative and quality blog it will really help in understanding multithreading

    ReplyDelete
  3. So Informative Blog site ..... Appreciate it

    ReplyDelete
  4. Good one .. Helped to understand this concept

    ReplyDelete
  5. Most informative information

    ReplyDelete
  6. Nice and informative content

    ReplyDelete
  7. Nice 👍👍👍👍👍👏😊 very good information

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. You show great attention to detail!

    ReplyDelete
  10. One of the Useful info for Multithreading seekers

    ReplyDelete
  11. Most informative information

    ReplyDelete
  12. Very informative and significant 👍

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete

Post a Comment