0% found this document useful (0 votes)
15 views25 pages

Chap2 Multithreading Notes

Multithreading is a programming concept that allows multiple threads to execute concurrently within a single process, improving performance and CPU utilization. In Java, multithreading is supported through the Thread class, Runnable interface, and Executor framework, offering advantages like better CPU utilization and faster response times, but also introduces complexities such as synchronization issues and debugging challenges. The document outlines the lifecycle of a thread, methods for thread creation, thread priority, and synchronization mechanisms to manage shared resources.

Uploaded by

wonderboy49282
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)
15 views25 pages

Chap2 Multithreading Notes

Multithreading is a programming concept that allows multiple threads to execute concurrently within a single process, improving performance and CPU utilization. In Java, multithreading is supported through the Thread class, Runnable interface, and Executor framework, offering advantages like better CPU utilization and faster response times, but also introduces complexities such as synchronization issues and debugging challenges. The document outlines the lifecycle of a thread, methods for thread creation, thread priority, and synchronization mechanisms to manage shared resources.

Uploaded by

wonderboy49282
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

MULTITHREADING

➢ Introduction to Multithreading.

• Multithreading is a programming concept in which multiple


threads execute concurrently within a single process.

• Instead of executing one task at a time (sequentially), a


multithreaded program can perform multiple tasks
simultaneously, improving performance and better utilization
of CPU resources.

• multithreaded program can perform multiple tasks


simultaneously, improving performance and better utilization
of CPU resources.

• In Java, multithreading is a core feature that allows a


program to run two or more parts of code at the same time.

• Example (Real-world analogy) A web browser:

✔ One thread loads a webpage

✔ Another thread plays a video

✔ Another thread handles user input

• All these tasks run at the same time, making the application
responsive.
➢ What is a Thread?

• A thread is the smallest unit of execution within a process.

1. A process is a program in execution

2. A thread is a lightweight sub-process inside a process

• Characteristics of a Thread :

1. Shares memory with other threads of the same process

2. Has its own:

✔ Program counter

✔ Stack

✔ Local variables

• Process vs Thread :

Process Thread

Heavyweight Lightweight

Has its own memory Shares memory

Slower context switching Faster context switching

Independent execution Dependent on process


➢ Multithreading in Java :

• Java provides built-in support for multithreading through:

◦ Thread class

◦ Runnable interface

◦ Executor framework

• Java uses time-sharing and priority-based scheduling to


manage threads.

➢ Advantages of Multithreading :

1. Improved Performance.

• Multiple tasks run in parallel

• Efficient use of multi-core processors

• Example:

◦ One thread reads data, another processes it, another


writes output.

2. Better CPU Utilization

• CPU remains busy instead of waiting for I/O operations.

• Reduces idle time.


3. Faster Response Time

• User interface remains responsive

• Background tasks do not block the main program

• Example:

◦ Downloading a file while continuing to use the


application.

4. Resource Sharing

• Threads share memory and resources

• Reduces memory overhead compared to multiple


processes

5. Scalability

• Applications can handle more users or tasks efficiently

• Widely used in web servers, databases, and enterprise


applications
➢ Disadvantages of Multithreading :

1. Complexity

• Multithreaded programs are harder to design, understand,


and debug

• Logic becomes complex due to concurrent execution

2. Synchronization Issues

• Shared resources can cause:

a) Race conditions

b) Inconsistent data

• Requires synchronization (synchronized, locks)

3. Deadlock

• Two or more threads wait indefinitely for each other’s


resources

• Example:

i. Thread A holds Resource 1 and waits for Resource 2

ii. Thread B holds Resource 2 and waits for Resource 1


4. Context Switching Overhead

• CPU switching between threads takes time

• Too many threads can reduce performance

5. Difficult Debugging and Testing

• Errors may occur randomly

• Bugs may not appear every time the program runs


➢ When to Use Multithreading :

• Multithreading is best used when:

1. Tasks are independent

2. Program needs high performance

3. Application requires responsiveness

4. System has multi-core processors

• Avoid multithreading when:

1. Tasks are simple and sequential.

2. Application is small and lightweight.


➢ LifeCycle of a Thread : In Java, a thread goes through a well-
defined set of states from creation to termination. This sequence is
called the Thread Lifecycle.
1. New (Born) State :

▪ A thread is created but not yet started (At this stage, the
thread is not running)

▪ Memory is allocated, but the CPU has not assigned time.

▪ Created using the Thread class or Runnable interface.

2. Runnable (Ready) State :

▪ The thread is ready to run and waiting for CPU time.

▪ Enters this state when start() is called.

▪ The thread may run at any time, depending on the scheduler.

[Link]( );
3. Running State :

▪ The thread is currently executing instructions.

▪ CPU scheduler selects it from the runnable pool.

▪ Only one thread per core can be running at a time.

4. Blocked / Waiting State (Thread does not consume CPU in


this state.) : A running thread can temporarily stop execution
due to:

▪ Blocked :Waiting to acquire a lock (synchronization).

▪ Waiting : Waiting indefinitely for another thread’s action.

wait ( );
join( );

▪ Timed Waiting :Waiting for a specific time.

sleep (1000 );
wait( 1000);
5. Terminated (Dead) State :

▪ Thread finishes execution or is stopped.

▪ Cannot be restarted.

▪ Once dead, the thread is destroyed forever.

public void run( ) {


// task completed }

➢ Thread Creation : A thread is a lightweight sub-process that


allows a program to perform multiple tasks simultaneously.

In Java, threads can be created in two main ways:

1. By extending the Thread class

2. By implementing the Runnable interface


1. Thread Creation Using Thread-Class :

◦ Java provides a built-in Thread class in [Link].

◦ We create a new class that extends Thread.

◦ Override the run() method.

◦ Call start() to begin execution.

◦ run() contains the task

◦ start() creates a new thread and calls run() internally


2. Thread Creation using Runnable Interface :

◦ Runnable is a functional interface

◦ The class implements Runnable

◦ The run() method defines the task

◦ Thread object is created by passing Runnable object


➢ Thread Priority in Java :

• In Java, Thread Priority is a mechanism used to indicate the


relative importance of threads to the thread scheduler.

• It helps the CPU decide which thread should be executed


first when multiple threads are ready to run.

• Thread priority is defined in the Java Thread class.

➢ What is Thread Priority?

• Thread priority is an integer value assigned to a thread that


hints to the JVM scheduler about the order of execution.

• Higher priority thread → More chance to get CPU time

• Lower priority thread → Less chance to get CPU time

• However, priority does NOT guarantee execution order. It


only provides a hint to the operating system scheduler.

➢ Priority Range in Java :

◦ Java supports 10 priority levels.

◦ By default, every thread has priority 5 (NORM_PRIORITY).


Priority Constant Value Meaning
Thread.MIN_PRIORITY 1 Lowest priority
Thread.NORM_PRIORITY 5 Default priority
Thread.MAX_PRIORITY 10 Highest priority

➢ Methods Used for Thread Priority :

1. setPriority() : Used to assign priority to a thread.

2. GetPriority() : Used to check the priority of a thread.

T1. GetPriority();

➢ Important Points About Thread Priority:

• Priority must be between 1 and 10.

• If priority is set outside this range

→ IllegalArgumentException.
• Child thread inherits priority from parent thread.

• JVM may ignore thread priority depending on OS.

• High priority does not mean immediate execution.

➢ Example Program :
➢ Execution of Thread Application : Running Multiple Threads
in Java

◦ A thread application in Java is a program where multiple


threads execute concurrently (simultaneously).

◦ Each thread represents a separate path of execution, enabling


better CPU utilization and improved performance.

1. The first way is to create a class which extends thread class and
then create the instance of that class.

2. This extended class must override method run().

3. It must also call start( ) method.

4. The Thread class is defined in package [Link]; so we have to


import it.

5. The following code segment tells the definition:


6. This will create a new class Count and overrides method run().
The program 2.8 shows how to write Thread program.

PROGRAM : For Multiple Threads.


OUTPUT :
7. This output may change PC to PC. In this program, two threads
main thread and MyThread (count) runs simultaneously.

8. In the above example, MyThread suspends threads for 500


millisecond by calling its sleep method.

9. The MainThread first get control of CPU and count as 1 and then
suspended for 1000 milliseconds.

PROGRAM : To use super in Threading.


OUTPUT
Synchronization and Interthread communication

➢ Synchronization in Java :

◦ Synchronization is a process of controlling access of multiple


threads to shared resources (like variables, objects, files) to
avoid data inconsistency.

◦ When multiple threads try to modify the same data at the same
time, it leads to a problem called Race Condition.

➢ Types of Synchronization in Java

1. Method Level Synchronization

2. Block Level Synchronization

3. Static Synchronization

➢ What is Critical Section?

◦ The part of code where shared resources are accessed is called


Critical Section.

◦ Synchronization ensures:

◦ Only one thread executes critical section at a time.


➢ Inter-Thread Communication in Java :

• Inter-thread communication is a mechanism by which:

➢ One thread waits

➢ Another thread notifies

• Used when threads depend on each other.

➢ Methods Used (from Object class)

Method Purpose

wait() Makes thread wait

notify() Wakes up one waiting thread

notifyAll() Wakes up all waiting threads

➢ Difference Between sleep() and wait()

sleep() wait()

Belongs to Thread class Belongs to Object class

Does not release lock Releases lock

Used for delay Used for communication

You might also like