top
upGrad KnowledgeHut SkillFest Sale!

Search

Java Tutorial

Multithreading in java Java multithreading is a process of simultaneously executing multiple threads. A thread is the smallest processing unit, a lightweight sub-process. Multiprocessing and multithreading are both used for multitasking purposes. However, as threads use a shared memory region, we use multithreading as multiprocessing. They do not allocate distinct memory region so memory is saved, and it takes less time to switch context between the threads than process. Advantages of Multithreading in java It does not block the user because threads are autonomous and various activities can be performed simultaneously. You can do many operations together, so it's time-saving. Threads are independent, so if an exception occurs in a single thread, it will not affect other threads. For many things, the Java runtime system depends on threads. Threads reduce inefficiency by preventing CPU cycles from being wasted. In several states there are threads. These states are as follows: New – When we create a thread class example, a thread is in a new state. Runnable – The thread of Java is executing/running. Suspended – It is possible to suspend a running thread that temporarily suspends its activity. It is then possible to resume a suspended thread, enabling it to pick up where it left off. Blocked – When waiting for a resource, a java thread can be blocked. Terminated – A thread that stops its implementation instantly at any specified moment can be terminated. It cannot be restarted once a thread is finished. Thread Class and Runnable Interface The multithreading system of Java is based on the Thread class, its methods, and the Runnable interface of its companion. Your program will either extend the Thread or implements the Runnable interface to generate a new thread. The class of threads describes several methods for managing threads. The table below shows the same thing: Method DescriptiongetNameIt is used to obtain thread’s namegetPriorityIt is used to get thread’s priorityisAliveIt is used to determine if a thread is still runningjoinIt waits for a thread to terminaterunIt is the entry point for the threadsleepIt is used to suspend a thread for a period of timestartIt is used to start a thread by calling its run methodJava lets you create a thread in the below 2 ways:-  By implementing the Runnableinterface.By extending the ThreadRunnable Interface A class that implements the Runnable interface is the easiest way to create a thread. A class only needs to implement a single method called run() to implement the Runnable interface, which is declared as follows:public void run( ) Inside run( ), we will have the code that constitutes the new thread. Example: public class MyFirstThreadClass implements Runnable {  public void run(){  System.out.println("My thread class is running");  }   } To run the run() method of a thread, pass an instance of MyFirstThreadClass to a Thread in its constructo. Here is how that is done:Thread t1 = new Thread(new MyFirstThreadClass ());  t1.start(); When the thread is started it will call the run() method of the MyFirstThreadClass instance instead of executing its own run() method. The above example would print out the text “My thread class is running“. Extending Java Thread The second way to create a thread is to create a new class that extends the thread, then override the method run() and then create an instance of that class. The run() method is what the thread runs after calling start(). Here is an instance of generating a subclass of Java Thread: public class MyFirstThreadClass extends Thread {  public void run(){  System.out.println("My thread class is running");  }  } To create and start the above thread you can do like this: MyFirstThreadClass t5 = new MyFirstThreadClass ();  T5.start(); When the run() method executes it will print out the text “My thread class is running “. Creating Multiple Threads in java class MyFirstThreadClass implements Runnable {     private Thread t;     private String myThreadName;     MyFirstThreadClass ( String myName) {        myThreadName = myName;        System.out.println("Creating " +  myThreadName);     }     public void run() {        System.out.println("Executing " +  myThreadName);        try {           for(int i = 4; i > 0; i--) {              System.out.println("Thread: " + myThreadName + ", " + i);              Thread.sleep(50);           }        } catch (InterruptedException e) {           System.out.println("Thread " +  myThreadName + " interrupted.");        }        System.out.println("Thread " +  myThreadName + " exiting.");     }     public void start () {        System.out.println("Starting " +  myThreadName );        if (t == null) {           t = new Thread (this, myThreadName);           t.start ();        }     }  }  public class TestThread {     public static void main(String args[]) {        MyFirstThreadClass R1 = new MyFirstThreadClass ( "Thread-1");        R1.start();        MyFirstThreadClass R2 = new MyFirstThreadClass ( "Thread-2");        R2.start();     }     } The output from this program is shown here: Creating Thread-1  Starting Thread-1  Creating Thread-2  Starting Thread-2  Executing Thread-1  Thread: Thread-1, 4  Executing Thread-2  Thread: Thread-2, 4  Thread: Thread-1, 3  Thread: Thread-2, 3  Thread: Thread-1, 2  Thread: Thread-2, 2  Thread: Thread-1, 1  Thread: Thread-2, 1  Thread Thread-1 exiting.  Thread Thread-2 exiting.
logo

Java Tutorial

Java Multithreading

Java

Multithreading in java 

Java multithreading is a process of simultaneously executing multiple threads. 

A thread is the smallest processing unit, a lightweight sub-process. Multiprocessing and multithreading are both used for multitasking purposes. 

However, as threads use a shared memory region, we use multithreading as multiprocessing. They do not allocate distinct memory region so memory is saved, and it takes less time to switch context between the threads than process. 

Advantages of Multithreading in java 

  • It does not block the user because threads are autonomous and various activities can be performed simultaneously. 
  • You can do many operations together, so it's time-saving. 
  • Threads are independent, so if an exception occurs in a single thread, it will not affect other threads. 

For many things, the Java runtime system depends on threads. Threads reduce inefficiency by preventing CPU cycles from being wasted. 

In several states there are threads. These states are as follows: 

  • New – When we create a thread class example, a thread is in a new state. 
  • Runnable – The thread of Java is executing/running. 
  • Suspended It is possible to suspend a running thread that temporarily suspends its activity. It is then possible to resume a suspended thread, enabling it to pick up where it left off. 
  • Blocked – When waiting for a resource, a java thread can be blocked. 
  • Terminated – A thread that stops its implementation instantly at any specified moment can be terminated. It cannot be restarted once a thread is finished. 

Multithreading in java

Thread Class and Runnable Interface 

The multithreading system of Java is based on the Thread class, its methods, and the Runnable interface of its companion. Your program will either extend the Thread or implements the Runnable interface to generate a new thread. 

The class of threads describes several methods for managing threads. The table below shows the same thing: 

Method Description
getNameIt is used to obtain thread’s name
getPriorityIt is used to get thread’s priority
isAliveIt is used to determine if a thread is still running
joinIt waits for a thread to terminate
runIt is the entry point for the thread
sleepIt is used to suspend a thread for a period of time
startIt is used to start a thread by calling its run method

Java lets you create a thread in the below 2 ways:-  

  • By implementing the Runnableinterface.
  • By extending the Thread

Runnable Interface 

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

A class only needs to implement a single method called run() to implement the Runnable interface, which is declared as follows:

public void run( ) 

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

Example: 

public class MyFirstThreadClass implements Runnable { 
public void run(){ 
System.out.println("My thread class is running"); 
   }  
} 

To run the run() method of a thread, pass an instance of MyFirstThreadClass to a Thread in its constructo. Here is how that is done:

Thread t1 = new Thread(new MyFirstThreadClass ()); 
t1.start(); 

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

Extending Java Thread 

The second way to create a thread is to create a new class that extends the thread, then override the method run() and then create an instance of that class. The run() method is what the thread runs after calling start(). Here is an instance of generating a subclass of Java Thread: 

public class MyFirstThreadClass extends Thread { 
     public void run(){ 
     System.out.println("My thread class is running"); 
   } 
} 

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

MyFirstThreadClass t5 = new MyFirstThreadClass (); 
T5.start(); 

When the run() method executes it will print out the text “My thread class is running “. 

Creating Multiple Threads in java 

class MyFirstThreadClass implements Runnable { 
   private Thread t; 
   private String myThreadName; 
   MyFirstThreadClass ( String myName) { 
      myThreadName = myName; 
      System.out.println("Creating " +  myThreadName); 
   } 
   public void run() { 
      System.out.println("Executing " +  myThreadName); 
      try { 
         for(int i = 4; i > 0; i--) { 
            System.out.println("Thread: " + myThreadName + ", " + i); 
            Thread.sleep(50); 
         } 
      } catch (InterruptedException e) { 
         System.out.println("Thread " +  myThreadName + " interrupted."); 
      } 
      System.out.println("Thread " +  myThreadName + " exiting."); 
   } 
   public void start () { 
      System.out.println("Starting " +  myThreadName ); 
      if (t == null) { 
         t = new Thread (this, myThreadName); 
         t.start (); 
      } 
   } 
} 
public class TestThread { 
   public static void main(String args[]) { 
      MyFirstThreadClass R1 = new MyFirstThreadClass ( "Thread-1"); 
      R1.start(); 
      MyFirstThreadClass R2 = new MyFirstThreadClass ( "Thread-2"); 
      R2.start(); 
   }    
} 

The output from this program is shown here: 

Creating Thread-1 
Starting Thread-1 
Creating Thread-2 
Starting Thread-2 
Executing Thread-1 
Thread: Thread-1, 4 
Executing Thread-2 
Thread: Thread-2, 4 
Thread: Thread-1, 3 
Thread: Thread-2, 3 
Thread: Thread-1, 2 
Thread: Thread-2, 2 
Thread: Thread-1, 1 
Thread: Thread-2, 1 
Thread Thread-1 exiting. 
Thread Thread-2 exiting. 

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

protective orders in virginia

Keep sharing blogs like this one; they are quite good. You have given everyone in this blog access to a wealth of information.

Johnfrance

Thank you for your valuable information.

sam

Thank you for this wonderful article!

Belay Abera

This article was really helpful to me, thank you!

dfsdf

super article!