[Go to site: main page, start]

0% found this document useful (0 votes)
6 views15 pages

Java Multithreading - Complete Interview Master Notes

The document provides comprehensive notes on Java multithreading concepts, including definitions, key points, and code examples for various topics such as thread creation, synchronization, thread states, and inter-thread communication. It covers differences between Thread class and Runnable interface, as well as details on thread safety, deadlocks, and the Executor Framework. Additionally, it explains advanced concepts like Callable, Future, and ReentrantLock, making it a valuable resource for interview preparation in Java multithreading.

Uploaded by

souravsikdar252
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views15 pages

Java Multithreading - Complete Interview Master Notes

The document provides comprehensive notes on Java multithreading concepts, including definitions, key points, and code examples for various topics such as thread creation, synchronization, thread states, and inter-thread communication. It covers differences between Thread class and Runnable interface, as well as details on thread safety, deadlocks, and the Executor Framework. Additionally, it explains advanced concepts like Callable, Future, and ReentrantLock, making it a valuable resource for interview preparation in Java multithreading.

Uploaded by

souravsikdar252
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

⚡ Java Multithreading – Complete

Interview Master Notes

🔹 Q1. What is multithreading in Java and why is it used?


💬 Interview Answer:
🧵🧵
⚡ 🖥️ 📱
Multithreading is the ability of a Java program to execute multiple threads concurrently . It
is used to improve performance , CPU utilization , and responsiveness —especially in
tasks like I/O operations, background processing, and parallel computation.

📌 Key Points:
●​ 🧠 Threads share the same memory.​
●​ 🪶 Lightweight compared to processes.​
●​ 🎮 Used in games, servers, UI apps, and real-time systems.​
class Task extends Thread {
public void run() {
[Link]("Task running in: " +
[Link]().getName());
}

public static void main(String[] args) {


Task t1 = new Task();
Task t2 = new Task();
[Link]();
[Link]();
}
}
🔹 Q2. Difference between Thread class and Runnable
interface
🧵 Thread Class 🔄 Runnable Interface
Extend a class Implement an interface

No multiple inheritance ❌ Supports multiple inheritance ✅


Less flexible More flexible & preferred
// Using Thread
class A extends Thread {
public void run() {
[Link]("Thread class");
}
}

// Using Runnable
class B implements Runnable {
public void run() {
[Link]("Runnable interface");
}

public static void main(String[] args) {


new A().start();
new Thread(new B()).start();
}
}

🔹 Q3. How do you create a thread in Java?


🛠️ Two ways:
●​ 🧵 Extend Thread​
●​ 🔄 Implement Runnable​
class MyThread extends Thread {
public void run() {
[Link]("By extending Thread");
}
}

class MyRunnable implements Runnable {


public void run() {
[Link]("By implementing Runnable");
}

public static void main(String[] args) {


new MyThread().start();
new Thread(new MyRunnable()).start();
}
}

🔹 Q4. Difference between start() and run()


💬 Interview Answer:
start() creates a new thread and calls run() internally.​
Calling run() directly executes it like a normal method (no new thread).

class Demo extends Thread {


public void run() {
[Link]("Running in: " +
[Link]().getName());
}

public static void main(String[] args) {


Demo d = new Demo();
[Link](); // main thread
[Link](); // new thread
}
}
📤 Output shows different thread names.

🔹 Q5. What are thread states in Java?


📍 States:
●​ NEW​

●​ RUNNABLE​

●​ BLOCKED​

●​ WAITING​

●​ TIMED_WAITING​

●​ TERMINATED​

class StateDemo extends Thread {


public void run() {
try {
[Link](1000);
} catch (Exception e) {}
}

public static void main(String[] args) throws Exception {


StateDemo t = new StateDemo();

[Link]([Link]()); // NEW
[Link]();
[Link]([Link]()); // RUNNABLE
[Link](200);
[Link]([Link]()); // TIMED_WAITING
[Link]();
[Link]([Link]()); // TERMINATED
}
}
🔹 Q6. What is synchronization? Why is it needed?
💬 Interview Answer:
Synchronization controls access to shared resources so that only one thread can execute a
critical section at a time. It prevents data inconsistency caused by concurrent modification.

class Counter {
int count = 0;

synchronized void increment() {


count++;
}

public static void main(String[] args) throws Exception {


Counter c = new Counter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) [Link]();
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) [Link]();
});

[Link](); [Link]();
[Link](); [Link]();

[Link]([Link]); // Always 2000


}
}

🔹 Q7. Synchronized method vs synchronized block


🔒 Synchronized Method 🎯 Synchronized Block
Locks whole method Locks specific part

Less flexible More efficient


class Printer {
void print() {
[Link]("Outside lock");

synchronized (this) {
[Link]("Inside lock");
}
}
}

📌 Use block when only part of method needs protection.

🔹 Q8. What is deadlock? How to avoid it?


💬 Interview Answer:
Deadlock occurs when two or more threads wait forever for each other’s locks.

class DeadlockDemo {
static final Object A = new Object();
static final Object B = new Object();

public static void main(String[] args) {


Thread t1 = new Thread(() -> {
synchronized (A) {
synchronized (B) {
[Link]("Thread 1");
}
}
});

Thread t2 = new Thread(() -> {


synchronized (B) {
synchronized (A) {
[Link]("Thread 2");
}
}
});

[Link]();
[Link](); // Deadlock possible
}
}

🚫 Avoid by:
●​ Lock ordering​

●​ Using tryLock()​

●​ Avoid nested locks​

🔹 Q9. What is thread safety?


💬 Interview Answer:
A class is thread-safe if it behaves correctly when accessed by multiple threads simultaneously
without external synchronization.

class SafeCounter {
private int count = 0;

synchronized void inc() {


count++;
}

synchronized int get() {


return count;
}
}
🔹 Q10. What is race condition?
💬 Interview Answer:
Race condition occurs when multiple threads access and modify shared data concurrently, and
the result depends on execution order.

class Race {
static int x = 0;

public static void main(String[] args) throws Exception {


Thread t1 = new Thread(() -> x++);
Thread t2 = new Thread(() -> x++);

[Link](); [Link]();
[Link](); [Link]();

[Link](x); // May be 1 or 2
}
}

🛠️ Fix: Use synchronization or atomic variables.

🔹 Q11. Difference between wait(), sleep(), and join()


Method Belongs Releases Purpose
To Lock?

wait() Object ✅ Yes Inter-thread communication

sleep() Thread ❌ No Pause execution

join() Thread ❌ No Wait for another thread to finish

class Demo {
public static void main(String[] args) throws Exception {
Thread t = new Thread(() -> {
try {
[Link](1000);
[Link]("Child done");
} catch (Exception e) {}
});

[Link]();
[Link](); // main waits
[Link]("Main done");
}
}

🔹 Q12. What is volatile keyword?


💬 Interview Answer:
volatile ensures visibility of changes to a variable across threads. It prevents thread-local
caching.

class VolatileDemo {
volatile boolean running = true;

public void run() {


new Thread(() -> {
while (running) {}
[Link]("Stopped");
}).start();
}

public static void main(String[] args) throws Exception {


VolatileDemo v = new VolatileDemo();
[Link]();
[Link](1000);
[Link] = false;
}
}
Without volatile, loop may never stop.

🔹 Q13. What is ThreadLocal?


💬 Interview Answer:
ThreadLocal provides thread-confined variables—each thread gets its own copy.

class TL {
static ThreadLocal<Integer> tl = [Link](() -> 0);

public static void main(String[] args) {


Runnable r = () -> {
[Link]([Link]() + 1);
[Link]([Link]().getName() + " :
" + [Link]());
};

new Thread(r).start();
new Thread(r).start();
}
}

🔹 Q14. Difference between notify() and notifyAll()


notify() notifyAll()

Wakes one Wakes all waiting


thread threads

Risk of deadlock Safer


class NotifyDemo {
public static void main(String[] args) {
Object lock = new Object();

Runnable r = () -> {
synchronized (lock) {
try {
[Link]();

[Link]([Link]().getName() + " resumed");


} catch (Exception e) {}
}
};

new Thread(r).start();
new Thread(r).start();

synchronized (lock) {
[Link]();
}
}
}

🔹 Q15. What is a daemon thread?


💬 Interview Answer:
A daemon thread runs in background and dies automatically when all user threads finish.

class DaemonDemo {
public static void main(String[] args) {
Thread t = new Thread(() -> {
while (true) [Link]("Running...");
});

[Link](true);
[Link]();

[Link]("Main ends");
}
}

JVM exits once main thread ends.


🔹 Q16. What is Executor Framework?
💬 Interview Answer:
Executor Framework manages a pool of threads and decouples task submission from task
execution. It improves performance, scalability, and resource management.

import [Link].*;

class ExecDemo {
public static void main(String[] args) {
ExecutorService ex = [Link](2);

[Link](() -> [Link]("Task 1"));


[Link](() -> [Link]("Task 2"));

[Link]();
}
}

🔹 Q17. Difference between Callable and Runnable


Runnable Callable

No return value Returns value

Cannot throw checked Can throw checked


exception exception

run() call()
import [Link].*;

class CallDemo {
public static void main(String[] args) throws Exception {
ExecutorService ex = [Link]();

Callable<Integer> c = () -> 10 + 20;


Future<Integer> f = [Link](c);

[Link]([Link]()); // 30
[Link]();
}
}

🔹 Q18. What is Future in Java?


💬 Interview Answer:
Future represents the result of an asynchronous computation. It allows checking status and
retrieving result later.

Future<Integer> f = [Link](() -> 5 * 5);

[Link]([Link]()); // false/true
[Link]([Link]()); // waits and returns 25

🔹 Q19. ReentrantLock vs synchronized


synchronize ReentrantLock
d

Implicit lock Explicit lock

No try-lock tryLock() supported

Auto release Must unlock manually


import [Link].*;

class LockDemo {
static Lock lock = new ReentrantLock();
static int count = 0;

static void inc() {


[Link]();
try {
count++;
} finally {
[Link]();
}
}
}

🔹 Q20. What is Inter-Thread Communication?


💬 Interview Answer:
It allows threads to coordinate using wait(), notify(), notifyAll() on a shared object.

class PC {
int data;
boolean available = false;

synchronized void produce(int x) throws Exception {


while (available) wait();
data = x;
available = true;
notify();
}

synchronized int consume() throws Exception {


while (!available) wait();
available = false;
notify();
return data;
}

public static void main(String[] args) {


PC pc = new PC();

new Thread(() -> {


try { [Link](100); } catch (Exception e) {}
}).start();

new Thread(() -> {


try { [Link]([Link]()); } catch (Exception
e) {}
}).start();
}
}

You might also like