Advertisement

Multithreading in Java | Benefits of Multithreading | Thread in Java

What Is Multithreading In Java


In Java, threads can be considered as the backbone of concurrency. A thread is an executable, lightweight unit that accesses common resources as well as its own call stack.

A Java application is one process and within this application, we can create multiple threads to achieve concurrency in java program.

An application running on the system can have multiple instances and these are usually called multi-doc applications. These application instances are called processes.Thread is assigned to each of these processes.

Depending on application requirements, the process can be assigned either a single thread or multiple threads. When the application process is assigned multiple threads, then we need to execute these multiple threads simultaneously.


Advantages of Multithreading in Java


This technique of executing multiple threads simultaneously is called multithreading.”

Simply multithreading means that -we have more than one thread running inside the same application.

Java has built-in support for multithreading.

multithreading

Multithreading is depicted in the above diagram. As shown above, there are multiple threads (thread1, thread2, and thread3)  that are running simultaneously inside an application.

For example, a desktop application providing functionality like editing, printing, saving, etc. is a multithreaded application. In this application, as printing is a background process, we can save the recent changes and we can also perform editing documents and printing documents concurrently by assigning these functions to calling their own threads.

The threads run parallel to each other in multithreaded applications  in a concurrent manner. Thus multithreading is also a part of Java concurrency. Note that though there are many threads, they share the memory area thereby saving on memory. Also, threads can switch contexts in no time.

Multithreading is useful as it provides concurrent execution of multiple parts of an application. Thus,  the application utilize the CPU time to its maximum and idle time is kept to a minimum as possible.

The following are some of the terms that we should know in relation to the multithreading as they are used here frequently.

Multitasking: In multitasking, the execution of more that one task at the same time.

Multithreading: Multithreading, is a process of executing multiple threads simultaneously.

Multiprocessing: In multiprocessing, multiple process is executed simultaneously. Like multitasking, but here more than one CPU are involved.

Parallel Processing: Parallel processing is a technique where multiple CPUs work concurrently.

Having discussed multithreading, the question arises as to why we need multithreading?


Benefits Of Multithreading


Multithreading has various benefits which helps us in efficient programming.

The below points will make it clear.

(1) Efficient Utilization of Single CPU Systems

When there is only one CPU with a single thread then the CPU time is wasted. When the thread is busy using other resources like IO, the CPU remains idle. We can improve this and better utilize the CPU by having multithreaded applications.

By using multithreading, if one thread is done with CPU, then the other thread can utilize it. With multiple threads, CPU idle time will be greatly minimized.

(2) Efficient Utilization of Multiple CPU Systems

Having more than one CPUs, the multithreaded applications are able to utilize multiple CPUs efficiently.

(3) Improved user experience with respect to Responsiveness

The responsiveness of the system improve with multithreaded applications. We don't experience the ‘GUI hanging’ when we have multiple threads executing various tasks in the application and the users do not need to wait to get a response for their requests.

Similarly, this is also the benefit of multithreading that the users are properly services in multithreaded systems.

How To Implement Concurrency In Java

The class using which we can implement concurrency in Java is java.lang.Thread class. This Thread class forms the basis of concurrency in Java program.

We also have this java.lang.Runnable interface that can be implemented by a Java class to abstract the thread behavior. For advanced application development, we use  the java.util.concurrent package available since Java 1.5.

Moving forward we will discuss concurrency in Java in detail. Let’s discuss and understand the concept of threads in Java in this tutorial. In our subsequent tutorials on multithreading, we will explore various multithreading and concurrency concepts.

What Is A Thread In Java

A single thread can be defined as the smallest unit of processing. In Java, we can use 'Thread' class for creating thread in our program.

There are two type of Java threads:

Types of Thread in Java

(1) User thread: When the application first start user thread is created. Then we can create as many user and daemon thread according to our requirement.

(2) Daemon thread: daemon threads are mainly used in the background and used for tasks like cleaning the application, etc.

Threads minimize the maintenance cost of the application. It also reduces the application overhead.

A single thread example is shown below:

public class Main{
        public static void main (String [] args){
            System.out.println("Hi, I am a thread");
        }  
    }

The above program will display “Hi, I am a thread” as when the application starts a user thread is created. In the above example, the main function is the starting point of application and it creates a user thread.

The Life Cycle Of A Thread

The following diagram shows the life cycle of a thread in Java.

Life cycle of thread in Java

As depict in the above diagram, a thread in Java has 5 states:

#1) New: Initially, the thread just created from Thread class has a ‘new’ state. It is yet to be started. This thread is also known as ‘born thread’.

#2) Runnable: In this state, the thread is invoked using the method ‘start’.

#3) Running: The thread instance’s start method is invoked and the thread begins running. This is called running state.

#4) Blocked: There are many threads in an application. These threads have to wait for another thread as their execution has to be synchronized.

#5) Terminated: Once the running process of the thread is over, the thread is terminated or its execution is stopped.

So, firstly a thread is created, then scheduled and later the scheduler run the thread. While the running thread may be blocked or suspended. Then it is resumed and while processing completes, the thread is executed and finally it is terminated.

Thread Priorities

Below are some points to be understand about thread priorities:

  • Thread priorities are integer numbers.
  • Using thread priority, we can make decision when we should switch from one thread state to another. This is the called context switching process.
  • Anytime a thread by its own release its control over CPU. Then the other thread with the highest priority can take over the CPU.
  • Similarly, a higher priority thread can gain he CPU form lower priority.
  • Thread class provides a setPriority () method which is used to set the priority for the thread.
  • We can also use these constants MIN_PRIORITY, MAX_PRIORITY, or NORM_PRIORITY in the place of integers.


Java Thread Using Runnable Interface


//class implements Runnable interface
class Runnable1 implements Runnable {
   private String message;
    //class constructor  
   public Runnable1(String message) {
      this.message = message;
   }
   //run method
   public void run() {
      while(true) {
         System.out.println(message);
      }
   }
}
public class Main {
   public static void main(String [] args) {
      //create first thread instance hello
      Runnable hello = new Runnable1("Greetings!!!");
      Thread thread1 = new Thread(hello);
      thread1.setDaemon(true);  //set this thread as daemon
      thread1.setName("hello");
      System.out.println("Starting 1st thread...");
      //start the thread
      thread1.start();     
      //create second thread instance bye     
      Runnable bye = new Runnable1("Bye Bye!!");
      Thread thread2 = new Thread(bye);    thread2.setPriority(Thread.MIN_PRIORITY);  //set priority to min
      thread2.setDaemon(true);      //set as daemon thread
      System.out.println("Starting Bye Bye thread...");
      //start the thread
      thread2.start();
      System.out.println("main()class is ending...");
   }
}

Learn about python Programming Click Here

Post a Comment

0 Comments