Java Interview Questions - Multithreading 🎯

beginner
18 min

Java Interview Questions - Multithreading 🎯

Welcome to this comprehensive guide on Java Multithreading! Let's embark on a journey to understand one of the most powerful features of Java that enables efficient and concurrent execution of multiple tasks. 📝

What is Multithreading in Java? 💡

Multithreading is a process where multiple threads run concurrently within a program. Each thread performs a specific task independently. This feature allows Java programs to be more efficient, responsive, and capable of handling multiple tasks at the same time.

Why Multithreading? 💡

  1. Improves Performance: Multithreading helps in reducing the response time of the program as multiple tasks can be performed simultaneously, leading to better performance.
  2. Efficient Use of Resources: It allows efficient use of system resources like CPU, memory, and I/O devices as each thread can perform its task without waiting for others to complete.
  3. Enhances User Experience: Multithreading plays a crucial role in creating interactive applications, such as GUI programs, where user actions can be responded to instantly.

Creating Threads in Java 💡

Java provides several ways to create threads, but the most common methods are:

  1. Extending Thread Class
  2. Implementing Runnable Interface

Creating Thread by Extending Thread Class 📝

java
public class MyThread extends Thread { public void run() { System.out.println("This is my thread!"); } public static void main(String[] args) { MyThread t = new MyThread(); t.start(); // Start the thread } }

Creating Thread by Implementing Runnable Interface 📝

java
public class MyRunnable implements Runnable { public void run() { System.out.println("This is my runnable thread!"); } public static void main(String[] args) { Thread t = new Thread(new MyRunnable()); t.start(); // Start the thread } }

Synchronization in Multithreading 💡

In multithreading, synchronization is necessary to ensure that only one thread accesses shared resources at a time to avoid conflicts and inconsistencies.

Java provides synchronized keyword and Lock interface for synchronization.

Synchronized Methods 📝

java
public class MySync { synchronized void printNumber(int number) { for (int i = 1; i <= 5; i++) { System.out.println(number + "-" + i); try { Thread.sleep(1000); // Simulate delay } catch (Exception e) { } } } public static void main(String[] args) { MySync obj = new MySync(); Thread t1 = new Thread(() -> obj.printNumber(1)); Thread t2 = new Thread(() -> obj.printNumber(2)); t1.start(); t2.start(); } }

In the above example, both threads access the printNumber method, which is synchronized. Therefore, only one thread can execute the method at a time.

Producer-Consumer Problem 📝

The Producer-Consumer problem is a classic example of synchronization in multithreading. It simulates a scenario where one thread (Producer) produces data and another thread (Consumer) consumes the data.

Here's a simple implementation using a Buffer class and synchronized methods:

java
public class Buffer { private int bufferSize = 5; private int buffer[] = new int[bufferSize]; private int count = 0; private int producer = 0; private int consumer = 0; public synchronized void put(int data) throws InterruptedException { while (count == bufferSize) { wait(); } buffer[producer] = data; producer = (producer + 1) % bufferSize; count++; notifyAll(); } public synchronized int get() throws InterruptedException { while (count == 0) { wait(); } int data = buffer[consumer]; consumer = (consumer + 1) % bufferSize; count--; notifyAll(); return data; } }

Quiz 💡

Quick Quiz
Question 1 of 1

What is the primary purpose of using Multithreading in Java?

Quick Quiz
Question 1 of 1

How can you create a thread in Java?