Wednesday, August 14, 2019

Java Multithreading Tutorial

This Java multithreading tutorial gives an overview of multithreading in Java, how thread is created and executed, how thread-based multitasking is different from process-based multitasking and how to facilitate inter-thread communication.


Multi-tasking – Thread and Process

Multi-tasking as the name suggests means performing multiple tasks at the same time. Operating systems do support multi-tasking for example you would be coding in Java using your favorite IDE while listening to songs in a player and chatting with your team member to clear some doubts about functionality. So at the same time there are at least 3 processes running IDE, player and a messenger. This is an example of process-based multitasking where more than two programs are running concurrently. In process-based multitasking, a program is the smallest unit of execution.

In thread-based multitasking a single program has two or more threads that can run concurrently. In thread-based multitasking, the thread is the smallest unit of execution. For example in your IDE. Building workspace task is going on in background while you are still writing code because these two tasks are performed by two separate threads.

Multi-threading in Java

Java programming language provides in-built support for multithreaded programming. To create a thread in Java you can use any of the following mechanism-

  1. Creating thread by extending the Thread class
  2. Creating thread by implementing the Runnable interface

Every thread created in Java is an object of Thread class. The code that has to be executed by a thread is provided inside the run method. Whether you implement Runnable interface or extend Thread class you need to override run() method and provide the code.

Thread creation example by implementing Runnable interface

class MyThread implements Runnable{
  @Override
  public void run() {
    System.out.println("In run method of MyThread- " 
      + Thread.currentThread().getName());    
  }    
}

public class ThreadDemo {
  public static void main(String[] args) { 
    System.out.println("In main method- " + Thread.currentThread().getName()); 
    // Passing runnable instance
    Thread thread = new Thread(new MyThread(), "MyThread");
    // Calling start method
    thread.start();
  }
}

Output

In main method- main
In run method of MyThread- MyThread

Thread creation example by extending Thread class

Same example when Thread class is extended. Since MyThread is already of type Thread so start() method is called directly using MyThread instance.

class MyThread extends Thread{
  @Override
  public void run() {
    System.out.println("In run method of MyThread- " 
      + Thread.currentThread().getName());    
  }    
}

public class ThreadDemo {
  public static void main(String[] args) { 
    System.out.println("In main method- " + Thread.currentThread().getName()); 
    // Calling start method
    new MyThread().start();
  }
}

Some of the important points about Java multithreading based on these two examples are as follows-

  • run() method has to be overridden, inside run() method you have to provide the functionality that is executed by the thread.
  • After creating thread instance you need to call start method on that thread. Once the thread is scheduled to start run() method will be implicitly called you don’t need to call run() method yourself. Refer What if run() Method Called Directly Instead of start() Method - Java Multi-Threading to know what happens when run() method is called directly.
  • When a Java program is executed one thread starts running immediately that thread is known as main thread in Java. Other threads are spawned from the main thread.

Types of threads

In Java multithreading there are two types of threads.

  1. User threads- Threads which are created to perform tasks related to the application where these threads are spawned.
  2. Daemon threads- Daemon threads are the thread that run in background to perform some tasks for the program as long as the program is running. Daemon threads in Java are suitable for performing general tasks which are not integral part of the application.

Lifecycle of a thread in Java

Java thread cycle is as follows-

  • New state- When a thread is created either by extending Thread class or implementing Runnable interface it is in "New State".
  • Runnable state- When start() method is called on the thread object, that schedules the thread to begin execution when it gets CPU cycle. This thread state is called Runnable.
  • Blocked state- A thread in the blocked state is waiting to acquire a lock so that it can enter a synchronized block/method.
  • Waiting state- A thread that is waiting indefinitely for another thread to perform a particular action is in the waiting state. A thread goes to waiting state duw to calling one of the following methods.
    • Object.wait with no timeout
    • Thread.join with no timeout
    • LockSupport.park
  • Timed_Waiting- A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. A thread is in the timed waiting state due to calling one of the following methods
    • Thread.sleep
    • Object.wait with timeout
    • Thread.join with timeout
    • LockSupport.parkNanos
    • LockSupport.parkUntil
  • Terminated- A thread that has completed execution is in terminated state.

Refer post Thread States (Thread Life Cycle) in Java Multi-Threading to know more about thread states with examples.

Advantages of Java multi-threading

  1. Multithreading helps you to keep idle time to a minimum as two or more threads are executed concurrently to maximize CPU utilization. With multiple threads one of the thread can execute while another is waiting for some resource.
  2. Thread-based multitasking has less overhead than the process-based multitasking.
  3. Multiple threads share the same address space with in a process saving memory requirement.
  4. Since threads are light weight so context switching from one thread to another is inexpensive.
  5. Since multiple threads are part of the same process so inter-thread communication is also inexpensive.

That's all for this topic Java Multithreading Tutorial. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Thread Priorities in Java Multi-Threading
  2. Inter-thread Communication Using wait, notify And notifyAll - Java Multithreading
  3. Synchronization in Java - Synchronized Method And Block
  4. Difference Between sleep And wait in Java Multi-Threading
  5. ThreadLocal Class in Java

You may also like-

  1. Difference Between equals() Method And equality Operator == in Java
  2. strictfp in Java
  3. Garbage Collection in Java
  4. CallableStatement Interface in Java-JDBC
  5. Removing Spaces Between Words in a String - Java Program
  6. Spring Transaction Management JDBC Example Using @Transactional Annotation
  7. Magic Methods in Python With Examples
  8. Java Multithreading Interview Questions And Answers