0% found this document useful (0 votes)
2 views16 pages

Java Multithreading

The document provides a comprehensive overview of Java multithreading, covering fundamental concepts such as threads, multithreading, and the advantages and disadvantages of using multiple threads. It details the life cycle of a thread, methods for creating threads, synchronization, inter-thread communication, deadlocks, and best practices in multithreading. Additionally, it introduces advanced topics like the Executor Framework, Callable and Future, and atomic classes for thread-safe operations.
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)
2 views16 pages

Java Multithreading

The document provides a comprehensive overview of Java multithreading, covering fundamental concepts such as threads, multithreading, and the advantages and disadvantages of using multiple threads. It details the life cycle of a thread, methods for creating threads, synchronization, inter-thread communication, deadlocks, and best practices in multithreading. Additionally, it introduces advanced topics like the Executor Framework, Callable and Future, and atomic classes for thread-safe operations.
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 – Detailed Notes

Unit: Java Multithreading

1. Introduction to Multithreading
What is a Thread?
A thread is the smallest unit of execution within a process. A Java program starts with one
thread called the main thread. Multiple threads can execute simultaneously, allowing a program
to perform multiple tasks at the same time.

Example

A web browser can:

• Download files
• Play music
• Display web pages
• Handle user input

All these tasks run using different threads.

What is Multithreading?
Multithreading is the process of executing two or more threads concurrently within a single
program.

Instead of waiting for one task to complete before starting another, multiple tasks execute
together.

Advantages

• Improves CPU utilization


• Faster execution
• Better responsiveness
• Efficient resource sharing
• Simplifies complex applications
• Supports parallel processing

Disadvantages

• Difficult debugging
• Race conditions
• Deadlocks
• Synchronization overhead

2. Process vs Thread
Process Thread
Independent execution unit Smallest execution unit
Has separate memory Shares process memory
Heavyweight Lightweight
Communication is slower Communication is faster
Creation is expensive Creation is inexpensive

3. Life Cycle of a Thread


A thread passes through several states during execution.

New

Runnable

Running

Blocked / Waiting / Timed Waiting

Runnable

Terminated

1. New

The thread object is created but start() has not been called.

Thread t = new Thread();

2. Runnable
The thread is ready for execution.

[Link]();

3. Running

CPU assigns execution to the thread.

4. Blocked / Waiting

Thread waits because of:

• Lock
• Sleep
• Join
• Wait

5. Terminated

Execution finishes.

4. Creating Threads in Java


Java provides two methods.

Method 1: Extending Thread Class


class MyThread extends Thread {

public void run() {


[Link]("Thread is running");
}

public static void main(String args[]) {

MyThread t = new MyThread();


[Link]();
}
}

Output
Thread is running

Advantages

• Simple

Disadvantages

• Cannot extend another class.

Method 2: Implementing Runnable Interface


class MyRunnable implements Runnable {

public void run() {


[Link]("Runnable Thread");
}

public static void main(String args[]) {

MyRunnable obj = new MyRunnable();

Thread t = new Thread(obj);

[Link]();
}
}

Advantages

• Supports multiple inheritance.


• Better object-oriented design.

5. Thread Class Methods


start()
Starts a new thread.
[Link]();

run()
Contains thread logic.

public void run() {

sleep()
Pauses execution.

[Link](1000);

Waits for 1000 milliseconds.

Example

for(int i=1;i<=5;i++){

[Link](i);

[Link](1000);
}

Output

1
2
3
4
5

(One second gap)

join()
Waits until another thread completes.

[Link]();

Example
Thread t=new Thread();

[Link]();

[Link]();

[Link]("Completed");

yield()
Temporarily pauses the current thread so another thread of the same priority may execute.

[Link]();

isAlive()
Checks whether thread is still executing.

[Link]();

Returns

true

or

false

currentThread()
Returns currently executing thread.

[Link]();

Example

[Link]([Link]().getName());

Output

main

getName()
Returns thread name.

[Link]();

setName()
Assigns thread name.

[Link]("Worker");

6. Thread Scheduler
Java uses a Thread Scheduler to decide which thread executes next.

Scheduling depends on:

• Priority
• Operating System
• JVM

It is not guaranteed that higher-priority threads always execute first.

7. Thread Priority
Priority values

1 -> MIN_PRIORITY

5 -> NORM_PRIORITY

10 -> MAX_PRIORITY

Example

Thread t1=new Thread();

[Link](8);

Retrieve priority

[Link]([Link]());
8. Synchronization
What is Synchronization?
Synchronization controls access to shared resources so that only one thread accesses a critical
section at a time.

Without synchronization:

• Incorrect output
• Data inconsistency
• Race condition

Example Without Synchronization


class Table{

void printTable(int n){

for(int i=1;i<=5;i++){

[Link](n*i);
}
}
}

Two threads calling this method may produce mixed output.

With Synchronization
class Table{

synchronized void printTable(int n){

for(int i=1;i<=5;i++){

[Link](n*i);
}
}
}

Only one thread executes the method at a time.


Types of Synchronization
1. Synchronized Method
synchronized void display(){

2. Synchronized Block
synchronized(this){

// Critical section
}

Advantages

• Prevents race conditions


• Ensures consistency

Disadvantages

• Slower execution
• Reduced concurrency

9. Inter-Thread Communication
Threads communicate using methods from the Object class.

Methods:

• wait()
• notify()
• notifyAll()

wait()
Thread releases the lock and waits.
[Link]();

notify()
Wakes one waiting thread.

[Link]();

notifyAll()
Wakes all waiting threads.

[Link]();

Producer–Consumer Concept

Producer creates data.

Consumer consumes data.

If data is unavailable:

Consumer waits.

When producer generates data:

Consumer resumes.

10. Deadlock
Definition
Deadlock occurs when two or more threads wait forever for each other to release locks.

Example

Thread A

Lock1
Waiting for Lock2
Thread B

Lock2
Waiting for Lock1

Neither proceeds.

Causes

• Nested locks
• Circular waiting
• Improper synchronization

Prevention

• Lock resources in same order


• Avoid unnecessary locks
• Use timeout locks

11. Daemon Thread


A daemon thread provides background services.

Examples

• Garbage Collector
• Timer Thread

Create daemon

Thread t=new Thread();

[Link](true);

[Link]();

Check

[Link]();
12. Thread Group
A ThreadGroup manages multiple threads together.

Example

ThreadGroup tg=new ThreadGroup("Workers");

Thread t1=new Thread(tg,"T1");

Thread t2=new Thread(tg,"T2");

Benefits

• Easier management
• Group interruption
• Group priority control

13. Executor Framework


Instead of creating threads manually, Java provides the Executor Framework.

Example

ExecutorService executor =
[Link](3);

[Link](() -> {

[Link]("Task");

});

[Link]();

Advantages

• Thread reuse
• Better performance
• Task scheduling
• Resource management
14. Callable and Future
Unlike Runnable, Callable:

• Returns a value
• Can throw exceptions

Example

Callable<Integer> task = () -> {

return 100;
};

ExecutorService executor =
[Link]();

Future<Integer> result =
[Link](task);

[Link]([Link]());

[Link]();

Output

100

15. Race Condition


A race condition occurs when multiple threads modify shared data simultaneously, causing
unpredictable results.

Example

count++;

If two threads execute this at the same time, updates may be lost.

Solution:

• Synchronization
• Atomic classes
• Locks
16. Volatile Keyword
The volatile keyword ensures that changes made by one thread are immediately visible to
other threads.

Example

class Example {

volatile boolean flag = true;


}

Without volatile, one thread may continue using a stale cached value.

17. Lock Interface


The Lock interface (from [Link]) provides more flexible locking than
synchronized.

Example

Lock lock = new ReentrantLock();

[Link]();

try {
[Link]("Critical Section");
} finally {
[Link]();
}

Advantages:

• Explicit lock/unlock
• Try-lock with timeout
• Fair locking options

18. Atomic Classes


Atomic classes provide thread-safe operations without explicit synchronization.
Examples:

• AtomicInteger
• AtomicLong
• AtomicBoolean

AtomicInteger count = new AtomicInteger(0);

[Link]();

[Link]([Link]());

19. Best Practices in Multithreading


• Prefer implementing Runnable or using the Executor Framework over extending Thread.
• Keep synchronized sections as small as possible.
• Avoid nested locks to reduce deadlock risk.
• Always release locks in a finally block.
• Use thread-safe collections (e.g., ConcurrentHashMap) when sharing data.
• Avoid excessive thread creation; use thread pools.
• Use volatile only for visibility, not for complex atomic operations.

20. Interview and Exam Questions


Short Questions

1. Define thread.
2. What is multithreading?
3. Difference between process and thread.
4. Explain the thread life cycle.
5. What is synchronization?
6. What is a daemon thread?
7. What is deadlock?
8. What is a race condition?
9. Difference between start() and run().
10. Difference between wait() and sleep().

Long Questions

1. Explain two methods of creating threads with examples.


2. Describe the thread life cycle with a diagram.
3. Explain synchronization and its types with examples.
4. Explain inter-thread communication using wait(), notify(), and notifyAll().
5. Discuss thread priorities and thread scheduling.
6. Explain the Executor Framework and its advantages.
7. Explain deadlock, race conditions, and methods to prevent them.

Quick Revision Summary


• Thread: Smallest unit of execution.
• Multithreading: Running multiple threads concurrently.
• Create Threads: Extend Thread or implement Runnable.
• Key Methods: start(), run(), sleep(), join(), yield(), isAlive().
• Synchronization: Prevents race conditions by allowing only one thread into a critical
section.
• Communication: wait(), notify(), notifyAll().
• Deadlock: Threads permanently waiting for each other's locks.
• Daemon Thread: Background service thread.
• Executor Framework: Efficient thread management using thread pools.
• Callable: Similar to Runnable but returns a value.
• Future: Retrieves the result of an asynchronous computation.
• Volatile: Ensures variable visibility across threads.
• Atomic Classes: Perform thread-safe updates without explicit synchronization.
• Lock Interface: Advanced locking with more flexibility than synchronized.

You might also like