0% found this document useful (0 votes)
18 views

UNIT 3 Object Oriented Programming

Uploaded by

kmozhi2112
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

UNIT 3 Object Oriented Programming

Uploaded by

kmozhi2112
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 100

Object Oriented

Programming
UNIT III
UNIT III EXCEPTION HANDLING AND MULTITHREADING
Exception Handling basics – Multiple catch Clauses – Nested try Statements – Java’s Built-in Exceptions – User
defined Exception. Multithreaded Programming: Java Thread Model–Creating a Thread and Multiple Threads –
Priorities – Synchronization – Inter Thread Communication Suspending –Resuming, and Stopping Threads –
Multithreading. Wrappers – Auto boxing.
EXCEPTION HANDLING IN JAVA
EXCEPTION HANDLING IN JAVA
Here’s the basic syntax:

try
{
// Code that may throw an exception
}
catch (ExceptionType e)
{
// Code to handle the exception
}
finally
{
// Optional block that executes after try/catch, regardless of whether an
exception occurred
}
EXCEPTION HANDLING IN JAVA
class expExample {
public static void main(String[] args) {
try {
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " +
e.getMessage());
}

finally {
System.out.println("This is the finally block");
}
}
}
EXCEPTION HANDLING IN JAVA
class expExample { Output
public static void main(String[] args) { ArithmeticException => / by zero
try { This is the finally block
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " +
e.getMessage());
}

finally {
System.out.println("This is the finally block");
}
}
}
EXCEPTION HANDLING IN JAVA
EXCEPTION HANDLING IN JAVA
public static void main(String[] args) {
// Test with an invalid age
// Custom Exception Class
try {
class AgeNotValidException extends Exception {
validate(15); // This will throw an
public AgeNotValidException(String message) {
exception
super(message);
} catch (AgeNotValidException e) {
}
System.out.println("Error: " +
}
e.getMessage());
}
// Main Class
public class AgeValidator {
// Test with a valid age
// Method to validate age
try {
public static void validate(int age) throws AgeNotValidException
validate(20); // This will pass
{
} catch (AgeNotValidException e) {
if (age < 18) {
System.out.println("Error: " +
throw new AgeNotValidException("Age must be 18 or
e.getMessage());
older.");
}
}
}
System.out.println("Valid age: " + age);
}
}
EXCEPTION HANDLING IN JAVA
Exception handling in Java (and in programming in general) provides several key benefits:

1. Improved Code Readability


● Exception handling separates error-handling code from regular code, making the code
easier to read and maintain. It allows developers to focus on the main logic without
cluttering it with error-checking code.
2. Robustness and Reliability
● By catching exceptions, you can prevent your program from crashing unexpectedly. This
leads to more robust applications that can handle unexpected situations gracefully.
3. Controlled Error Handling
● Exception handling allows you to manage errors in a centralized way, enabling consistent
responses to different types of errors. This leads to a more predictable application
behavior.
4. Resource Management
● With the use of finally blocks or try-with-resources statements (in Java 7 and later), you
can ensure that resources (like files or network connections) are closed properly, avoiding
EXCEPTION HANDLING IN JAVA
5. Debugging Aid
● Exceptions provide detailed information about errors, including stack traces. This helps in
diagnosing issues more easily during the development process.
6. Separation of Concerns
● Exception handling separates the normal flow of code from error-handling code, allowing
developers to implement complex error recovery mechanisms without affecting the main
logic.
7. Propagation of Errors
● Exceptions can be propagated up the call stack, allowing higher-level methods to handle
errors. This means that lower-level methods do not need to handle every possible error,
leading to cleaner code.
8. Flexibility
● Different types of exceptions can be handled differently. For instance, you might want to
log a FileNotFoundException but prompt the user for input in case of an
InputMismatchException.
EXCEPTION HANDLING IN JAVA

Feature Errors Exceptions

Definition Serious problems; not recoverable Conditions that can be handled

Subclass Subclass of Error Subclass of Exception

Recovery Not intended to be caught Intended to be caught

Handling Not typically handled Handled with try-catch

OutOfMemoryError,
Examples IOException, NullPointerException
StackOverflowError
EXCEPTION HANDLING IN JAVA
EXCEPTION HANDLING IN JAVA
EXCEPTION HANDLING IN JAVA
Checked Exceptions
Checked exceptions are exceptions that are checked at compile time. The compiler requires you to handle or declare them.
1. IOException: Thrown when an I/O operation fails or is interrupted.
2. SQLException: Thrown when there is an error accessing a database.
3. ClassNotFoundException: Thrown when a class cannot be located.
4. FileNotFoundException: A subclass of IOException, thrown when a file with the specified pathname does not exist.
5. InterruptedException: Thrown when a thread is waiting, sleeping, or otherwise occupied, and another thread interrupts it.
6. ParseException: Thrown when parsing a string into a number or date fails.
7. InstantiationException: Thrown when an application tries to create an instance of a class using the newInstance()
method but the class cannot be instantiated.
Unchecked Exceptions
Unchecked exceptions are not checked at compile time. They are subclasses of RuntimeException and typically indicate
programming errors.
8. NullPointerException: Thrown when trying to use a null reference where an object is required.
9. ArrayIndexOutOfBoundsException: Thrown when trying to access an invalid index of an array.
10. ArithmeticException: Thrown when an arithmetic operation fails, such as dividing by zero.
11. ClassCastException: Thrown when an invalid cast is attempted.
12. IllegalArgumentException: Thrown when a method receives an argument that is not acceptable.
13. NumberFormatException: Thrown when a string cannot be converted to a numeric type.
14. IndexOutOfBoundsException: Thrown when trying to access an invalid index in a collection, such as a list or string.
EXCEPTION HANDLING IN JAVA

EXAMPLES OF EXCEPTIONS
IN JAVA
EXCEPTION HANDLING IN JAVA
1. NullPointerException
Occurs when trying to access a method or variable on an object that is null.
Example:

public class NullPointerExample {


public static void main(String[] args) {
String str = null;
try {
System.out.println(str.length());
// This will throw NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught a NullPointerException: " +
e.getMessage());
}
}
}
EXCEPTION HANDLING IN JAVA
ArrayIndexOutOfBoundsException
Thrown when trying to access an index of an array that is out of bounds.

Example:

public class ArrayIndexExample {


public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
System.out.println(numbers[3]); // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught an ArrayIndexOutOfBoundsException: " + e.getMessage());
}
}
}
EXCEPTION HANDLING IN JAVA
ArithmeticException
Occurs when an illegal arithmetic operation is performed, such as dividing by zero.

Example:

public class ArithmeticExample {


public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught an ArithmeticException: " + e.getMessage());
}
}
}
EXCEPTION HANDLING IN JAVA
NumberFormatException
Thrown when trying to convert a string that does not have a valid format into a numeric type.
Example:
public class NumberFormatExample {
public static void main(String[] args) {
String invalidNumber = "abc";
try {
int num = Integer.parseInt(invalidNumber); // This will throw
NumberFormatException
} catch (NumberFormatException e) {
System.out.println("Caught a NumberFormatException: " + e.getMessage());
}
}
}
EXCEPTION HANDLING IN JAVA
IOException
Occurs when an I/O operation fails or is interrupted. This is a checked exception, so it must be declared or
caught.
Example:
import java.io.*;

public class IOExceptionExample {


public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("nonexistentfile.txt")); //
This will throw IOException
String line = reader.readLine();
System.out.println(line);
} catch (IOException e) {
System.out.println("Caught an IOException: " + e.getMessage());
}
}
}
EXCEPTION HANDLING IN JAVA
Multiple Catch Clauses
In Java, you can have multiple catch blocks to handle different types of exceptions that may arise from a single try block. This allows for
more granular error handling, letting you respond to different exceptions in different ways.
Syntax
try {
// Code that may throw exceptions
}
catch (ExceptionType1 e1) {
// Handle
ExceptionType1
}
catch (ExceptionType2 e2) {
// Handle
ExceptionType2
}
catch (ExceptionType3 e3) {
// Handle
ExceptionType3
}
finally {
EXCEPTION HANDLING IN JAVA
//Example Multiple catches
public class MultipleCatchExample {
public static void main(String[] args) {
try {
// Code that may throw exceptions
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // This will throw ArrayIndexOutOfBoundsException
// String text = null;
// System.out.println(text.length()); // This will throw NullPointerException
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds: " + e.getMessage());
}
catch (NullPointerException e) {
System.out.println("Null pointer exception: " + e.getMessage());
}
catch (Exception e) {
// This will catch any other exceptions
System.out.println("An exception occurred: " + e.getMessage());
} finally {
System.out.println("This block always executes.");
}
}}
EXCEPTION HANDLING IN JAVA
//Example Multiple catches
public class MultipleCatchExample {
public static void main(String[] args) {
try {
// Code that may throw exceptions
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // This will throw ArrayIndexOutOfBoundsException
// String text = null;
// System.out.println(text.length()); // This will throw NullPointerException
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds: " + e.getMessage());
}
catch (NullPointerException e) {
System.out.println("Null pointer exception: " + e.getMessage());
}
catch (Exception e) {
// This will catch any other exceptions
System.out.println("An exception occurred: " + e.getMessage());
} finally { Output
System.out.println("This block always executes."); Array index is out of bounds:
} // Null pointer exception: null
}} This block always executes.
EXCEPTION HANDLING IN JAVA

NESTED TRY STATEMENTS

In Java, nested try statements refer to the situation where one try-catch block is placed inside another try
block. This structure allows handling different exceptions that may arise in different parts of a program, especially in
scenarios where a specific exception can occur within another exception-prone code section.
EXCEPTION HANDLING IN JAVA
syntax for nested try-catch statements
try {
// Outer try block
// Code that may throw exceptions

try {
// Inner try block
// Code that may throw exceptions inside the inner try block
}
catch (ExceptionType1 e1) {
// Inner catch block for ExceptionType1
}
try {
// Another inner try block (optional)
// More code that may throw exceptions
}
catch (ExceptionType2 e2) {
// Inner catch block for ExceptionType2
}
// More code in the outer try block
}
catch (ExceptionType3 e3) { // Outer catch block for ExceptionType3 }

finally {
// Finally block for cleanup (optional)
// This will always execute, regardless of whether an exception occurred or not }
EXCEPTION HANDLING IN JAVA
public class NestedTryExample {
public static void main(String[] args) {
// Outer try block
try {
int[] numbers = {1, 2, 3};
// Nested (inner) try block 1
try {
System.out.println("Accessing index 5 of the array: " + numbers[5]);
// ArrayIndexOutOfBoundsException }
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException in inner try block 1: " +
e.getMessage()); }
// Nested (inner) try block 2
try {
int result = 10 / 0; // ArithmeticException
}
catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException in inner try block 2: " + e.getMessage());
}
// This line will still execute even if exceptions occur above
System.out.println("After inner try blocks."); }
catch (Exception e) {
// Outer catch block to catch any remaining exceptions
System.out.println("Caught exception in outer try block: " + e.getMessage());
}
finally {
System.out.println("Finally block always executes, at the end of all try-catch blocks.");
} } }
EXCEPTION HANDLING IN JAVA

OUTPUT

Caught ArrayIndexOutOfBoundsException in inner try block 1: Index 5 out of bounds for


length 3
Caught ArithmeticException in inner try block 2: / by zero
After inner try blocks.
Finally block always executes, at the end of all try-catch blocks.
EXCEPTION HANDLING IN JAVA
JAVA BUILT IN EXCEPTIONS
EXCEPTION HANDLING IN JAVA
JAVA BUILT IN EXCEPTIONS

Common Runtime Exceptions:

1. NullPointerException
○ Thrown when a program attempts to access an object through a null
reference.
Example:

String text = null;

System.out.println(text.length());

// Throws NullPointerException
EXCEPTION HANDLING IN JAVA
JAVA BUILT IN EXCEPTIONS

2. ArithmeticException
● Thrown when an illegal arithmetic operation occurs, such as division by zero.
Example:
int result = 10 / 0;
// Throws ArithmeticException

3. ArrayIndexOutOfBoundsException
● Thrown when trying to access an invalid index of an array.
Example:
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // Throws
ArrayIndexOutOfBoundsException
EXCEPTION HANDLING IN JAVA
JAVA BUILT IN EXCEPTIONS

4. ClassCastException
● Thrown when an object is cast to a class that it is not an instance of.
Example:
Object obj = new Integer(5);
String str = (String) obj; // Throws ClassCastException

5. NumberFormatException
● Thrown when an attempt to convert a string to a numeric type fails.
Example:
String num = "abc";
int n = Integer.parseInt(num);
// Throws NumberFormatException
EXCEPTION HANDLING IN JAVA
JAVA BUILT IN EXCEPTIONS

6. IllegalArgumentException
○ Thrown when a method receives an argument that is inappropriate or not expected.
7. IndexOutOfBoundsException
○ Thrown when attempting to access an invalid index in a list or array.
■ Subtypes: ArrayIndexOutOfBoundsException and
StringIndexOutOfBoundsException.
8. IllegalStateException
○ Thrown when a method is invoked at an illegal or inappropriate time, often because
an object is in an improper state.
9. UnsupportedOperationException
○ Thrown when an unsupported method is invoked (often in collections).
EXCEPTION HANDLING IN JAVA
JAVA BUILT IN EXCEPTIONS

Error Class
Errors in Java represent serious issues, often related to the environment (JVM) rather than the
program itself. These are not meant to be caught by typical applications.
Common Errors:
1. StackOverflowError
○ Thrown when the stack memory allocated to a program is exceeded, typically due to
deep recursion.
2. OutOfMemoryError
○ Thrown when the JVM runs out of memory to allocate new objects.
3. VirtualMachineError
○ A superclass for errors related to the JVM, such as OutOfMemoryError and
StackOverflowError.
4. AssertionError
○ Thrown when an assertion fails, usually when the -ea (enable assertions) flag is used
during runtime.
EXCEPTION HANDLING IN JAVA
USER DEFINED EXCEPTIONS IN JAVA

● What are User-Defined Exceptions?


○ Custom exceptions that programmers can create
to represent specific error conditions in their
applications.
○ Extend the Exception class or one of its
subclasses.
○ Useful for handling domain-specific errors that
the built-in exceptions don’t cover.
EXCEPTION HANDLING IN JAVA
USER DEFINED EXCEPTIONS IN JAVA

Steps to Create a User-Defined Exception


1. Define a class that extends Exception or RuntimeException.
2. Create constructors: Provide constructors in the class to accept
error messages and other data.
3. Throw and catch the user-defined exception using the throw and
try-catch blocks.
EXCEPTION HANDLING IN JAVA
USER DEFINED EXCEPTIONS IN JAVA
EXCEPTION HANDLING IN JAVA
USER DEFINED EXCEPTIONS IN JAVA
EXCEPTION HANDLING IN JAVA
USER DEFINED EXCEPTIONS IN JAVA
EXCEPTION HANDLING IN JAVA
USER DEFINED EXCEPTIONS IN JAVA

OUTPUT

Age is 20. Access Granted.


Caught the exception: Age is less than 18. Access Denied.
Program continues after exception handling...
MULTITHREADING IN JAVA
JAVA THREADS

What is a Thread?
● A thread is a lightweight process that allows multiple operations to execute
concurrently within a single program.
● Concurrency enables more efficient CPU usage and improved program
responsiveness.

Why Use Threads?


● To perform multiple tasks simultaneously (e.g., downloading files while
processing user inputs).
● Resource sharing among threads is easier and more efficient than process-
based multitasking.
MULTITHREADING IN JAVA
JAVA THREADS

Thread Definition:
A thread is the smallest unit of a program that can be scheduled for execution by the
operating system.
Key Characteristics of a Thread:

● Shares resources like memory and file handles with other threads within the
same process.
● Each thread has its own execution context (stack, program counter, etc.).
MULTITHREADING IN JAVA
JAVA THREADS

Thread Concepts
● Main Thread:
Every Java application starts with a main thread, which is created
automatically by the JVM.

● Creating Threads:
Threads can be created in Java by:
○ Extending the Thread class.
○ Implementing the Runnable interface.
MULTITHREADING IN JAVA
JAVA THREADS
MULTITHREADING IN JAVA

Differences Between Process-Based and Thread-Based Multitasking


● Process-Based Multitasking:
○ Each process is independent, with its own memory and resources.
○ Processes run in isolation from one another.
○ Heavyweight due to separate resource allocation.
● Thread-Based Multitasking:
○ Multiple threads exist within a single process.
○ Threads share the same memory and resources.
○ Lightweight, more efficient, less overhead than processes.
MULTITHREADING IN JAVA
MULTITHREADING IN JAVA

Why Choose Thread-Based Multitasking?


● Advantages of Threads:
○ Resource Sharing: Threads within the same process can easily share
data and resources.
○ Efficient CPU Utilization: Multithreading maximizes the usage of CPU
cycles.
○ Faster Context Switching: Thread switching is faster than process
switching.
○ Improved Responsiveness: A multithreaded program remains
responsive to user inputs during lengthy tasks.
STATES OF
A THREAD
MULTITHREADING IN JAVA
LIFE CYCLE OF A THREAD
MULTITHREADING IN JAVA
LIFE CYCLE OF A THREAD
MULTITHREADING IN JAVA

Thread Life Cycle


● Java Thread Life Cycle Stages:
1. New: The thread is created but not yet started.
2. Runnable: The thread is ready to run and is waiting for CPU time.
3. Running: The thread is executing its task.
4. Blocked/Waiting: The thread is waiting for a resource (e.g., I/O or
lock).
5. Terminated/Dead: The thread has completed its execution or is
aborted.
● State Transition: Threads transition between these states based on
events like method calls (start(), wait(), etc.) or resource availability.
MULTITHREADING IN JAVA

THE “main” THREAD


The “main” thread is a thread that begins running immediately when a
java
program starts up. The “main” thread is important for two reasons:

1. It is the thread form which other child threads will be spawned.


2. It must be the last thread to finish execution because it performs
various shutdown actions.

● Although the main thread is created automatically when our program


is started, it can be controlled through a Thread object.
● To do so, we must obtain a reference to it by calling the method
currentThread().
MULTITHREADING IN JAVA

EXAMPLE
class CurrentThreadDemo {
public static void main(String args[]) {
// Get the reference to the current thread (main thread)
Thread t =
Thread.currentThread();
// Print information about the current thread

System.out.println("Current Thread: " + t);


// Change the name of the main thread to "My Thread"
t.setName("My Thread");
// Print information about the thread after the name change

System.out.println("After name change: " + t);


try {
// Loop to count down from 5 to 1 with a delay of 1 second between each number
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000); // Pause for 1 second (1000 milliseconds)
}}
catch(InterruptedException e) {
MULTITHREADING IN JAVA

OUTPUT

Current Thread: Thread[main,5,main]


After name change: Thread[My Thread,5,main]
5
4
3
2
1
MULTITHREADING IN JAVA
CREATING THREADS IN JAVA

We can create threads by instantiating an object of type Thread. Java defines two
ways
to create threads:
1. By implementing Runnable interface (java.lang.Runnable)
2. By extending the Thread class (java.lang.Thread)
Example: Creating Threads by Implementing the Runnable Interface
// Step 1: Create a class that implements the Runnable interface
class MyRunnable implements Runnable {
// Step 2: Override the run() method
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(i + " - Thread is running by implementing Runnable
interface");
try {
Thread.sleep(1000); // Pause the thread for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}}}}
public class TestRunnable {
public static void main(String[] args) {
// Step 3: Create an instance of the MyRunnable class
MyRunnable myR = new
MyRunnable();
// Step 4: Create a Thread object and pass MyRunnable to the Thread constructor
Thread t1 = new Thread(myR);
// Step 5: Start the thread using the start() method
t1.start(); } }
MULTITHREADING IN JAVA

OUTPUT

1 - Thread is running by implementing Runnable interface


2 - Thread is running by implementing Runnable interface
3 - Thread is running by implementing Runnable interface
4 - Thread is running by implementing Runnable interface
5 - Thread is running by implementing Runnable interface
MULTITHREADING IN JAVA

Creating threads by extending Thread class:


Thread class provide constructors and methods to create and perform
operations on a thread.
Commonly used Constructors of Thread class:
● Thread()
● Thread(String name)
● Thread(Runnable r)
● Thread(Runnable r, String name)
All the above constructors creates a new thread.

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
MULTITHREADING IN JAVA

Here’s a list of the commonly used methods of the Thread class in Java:

1. void start()
2. void run()
3. static void sleep(long milliseconds)
4. void join()
5. void join(long millis)
6. void setPriority(int priority)
7. int getPriority()
8. static Thread currentThread()
9. void setName(String name)
10.String getName()
11.boolean isAlive()
12.void yield()
13.void interrupt()
14.boolean isInterrupted()
15.static boolean interrupted()
MULTITHREADING IN JAVA

Example: Creating Threads by Extending the Thread Class


// Step 1: Create a class that extends the Thread class
class MyThread extends Thread {
// Step 2: Override the run() method
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(i + " - Thread is running by extending Thread class");
try {
Thread.sleep(1000); // Pause the thread for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}}}}
public class TestThread {
public static void main(String[] args) {
// Step 3: Create an instance of the MyThread class
MyThread t1 = new MyThread();
// Step 4: Start the thread using the start() method
t1.start();
}}
MULTITHREADING IN JAVA

OUTPUT

1 - Thread is running by extending Thread class


2 - Thread is running by extending Thread class
3 - Thread is running by extending Thread class
4 - Thread is running by extending Thread class
5 - Thread is running by extending Thread class
MULTITHREADING IN JAVA
MULTITHREADING IN JAVA
MULTITHREADING IN JAVA
JAVA THREADS
MULTITHREADING IN JAVA

Importance of Multithreading

● Why Multithreading?
○ Enhanced Performance: Multithreading allows programs to perform multiple
tasks simultaneously, leading to better CPU utilization.
○ Increased Responsiveness: Programs remain responsive to user input while
executing background tasks (e.g., file downloads).
○ Real-Time Applications: Used in games, simulations, and real-time
processing where quick task switching is needed.
● Key Advantage: Concurrency allows for better management of computational
tasks in parallel.
MULTITHREADING IN JAVA

Thread Priorities and Their Effect on Execution


● Thread Priorities in Java:
○ Java assigns a priority level to each thread, ranging from
MIN_PRIORITY (1) to MAX_PRIORITY (10).
○ By default, threads are assigned a NORM_PRIORITY (5).
○ Priorities hint to the scheduler which thread should execute next.
● Effect on Execution:
○ Higher-priority threads are more likely to be selected for execution
by the CPU.
○ However, thread priorities do not guarantee execution order—it
depends on the JVM and operating system's thread scheduling
mechanism.
MULTITHREADING IN JAVA

How to Set Thread Priorities


● Setting Priorities in Java:
○ thread.setPriority(int priorityLevel);
○ Common priorities:
■ Thread.MIN_PRIORITY (1)
■ Thread.NORM_PRIORITY (5)
■ Thread.MAX_PRIORITY (10)
● Important Note:
○ Thread priorities should be used cautiously, as relying heavily
on them may result in unpredictable behavior in
multithreaded applications.
Example: Thread Priority in Java
// Step 1: Create a class that extends Thread
class PriorityThread extends Thread {
private int threadPriority;
// Constructor to set thread priority
public PriorityThread(int priority) {
this.threadPriority = priority;
this.setPriority(threadPriority); // Set the thread's priority }
// Override the run() method
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(getName() + " with priority " + threadPriority + " is running: " + i);
try {
Thread.sleep(500); // Pause the thread for 0.5 seconds
} catch (InterruptedException e) {
System.out.println(e);
} } } }
public class ThreadPriorityExample {
public static void main(String[] args) {
// Step 2: Create threads with different priorities
PriorityThread thread1 = new PriorityThread(Thread.MIN_PRIORITY); // Priority 1
PriorityThread thread2 = new PriorityThread(Thread.NORM_PRIORITY); // Priority 5
PriorityThread thread3 = new PriorityThread(Thread.MAX_PRIORITY); // Priority 10
// Step 3: Start the threads
thread1.start();
thread2.start();
thread3.start(); } }
MULTITHREADING IN JAVA

OUTPUT

Thread-0 with priority 1 is running: 1


Thread-2 with priority 10 is running: 1
Thread-1 with priority 5 is running: 1
Thread-0 with priority 1 is running: 2
Thread-2 with priority 10 is running: 2
Thread-1 with priority 5 is running: 2

MULTITHREADING IN JAVA
MULTITHREADING EXAMPLE PROGRAM
MULTITHREADING IN JAVA
MULTITHREADING EXAMPLE PROGRAM
MULTITHREADING IN JAVA
MULTITHREADING EXAMPLE PROGRAM
MULTITHREADING IN JAVA

OUTPUT

Number: 1
Message: Hello from the thread!
Number: 2
Number: 3
Message: Hello from the thread!
Number: 4
Number: 5
Message: Hello from the thread!
Message: Hello from the thread!
Message: Hello from the thread!
Both threads have finished execution.
MULTITHREADING IN JAVA

Thread Synchronization
Definition:
Thread Synchronization Thread synchronization is the concurrent execution of two or more
threads that share critical resources. When two or more threads need to use a shared resource, they
need some way to ensure that the resource will be used by only one thread at a time. The
process of ensuring single thread access to a shared resource at a time is called synchronization.
Threads should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts
may arise when parallel-running threads attempt to modify a common variable at the same time.

Why use Synchronization


1. To prevent thread interference.
2. To prevent consistency problem
MULTITHREADING IN JAVA

TYPES OF THREAD SYNCHRONIZATION


There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
● Synchronized method.
● Synchronized block.
● Static synchronization.
2. Cooperation (Inter-thread communication in java)
MULTITHREADING IN JAVA

Example: Synchronized Method in Java

// A shared class with a synchronized method to increment a counter


class Counter {
private int count = 0;
// Synchronized method to ensure mutual exclusive access to this method
public synchronized void increment() {
count++;
System.out.println(Thread.currentThread().getName() + " - Count: " + count);
}}
// A thread class that will call the synchronized method
class MyThread extends Thread {
Counter counter;
// Constructor to pass the shared Counter object
MyThread(Counter counter) {
this.counter = counter; }
//ctd………………………
MULTITHREADING IN JAVA

// Each thread will call the increment method 5 times


@Override
public void run() {
for (int i = 0; i < 5; i++) {
counter.increment(); // This method is synchronized
try {
Thread.sleep(100); // Adding a small delay for demonstration
} catch (InterruptedException e) {
System.out.println(e); } } } }

public class SynchronizedMethodExample {


public static void main(String[] args) {
// Create a single shared Counter object
Counter counter = new Counter();
// Create two threads that will share the same Counter object
MyThread t1 = new MyThread(counter);
MyThread t2 = new MyThread(counter);
// Start both threads
t1.start();
t2.start();
} }
MULTITHREADING IN JAVA

OUTPUT

Thread-0 - Count: 1
Thread-0 - Count: 2
Thread-0 - Count: 3
Thread-0 - Count: 4
Thread-0 - Count: 5
Thread-1 - Count: 6
Thread-1 - Count: 7
Thread-1 - Count: 8
Thread-1 - Count: 9
Thread-1 - Count: 10
MULTITHREADING IN JAVA
https://www.youtube.com/watch?v=mTzqVinpU1E&ab_channel=CrioDo
MULTITHREADING IN JAVA

Overview of Thread Management


● Definition of Thread Management
○ Controlling the lifecycle of threads.
● Importance of Effective Management
○ Ensures resource efficiency and application stability.
MULTITHREADING IN JAVA

Thread States
● 1. New
○ Thread is created.
● 2. Runnable
○ Thread is ready to run.
● 3. Blocked
○ Thread is waiting for a resource.
● 4. Suspended
○ Thread is temporarily paused.
● 5. Terminated
○ Thread has finished execution.
MULTITHREADING IN JAVA

Suspending Threads
● Definition:
○ Temporarily halting a thread's execution.
● How to Suspend:
○ Use methods like suspend() (deprecated in some
languages).
● Use Cases:
○ Pausing for resource availability or user input.
MULTITHREADING IN JAVA

Resuming Threads
● Definition:
○ Restarting a suspended thread.
● How to Resume:
○ Use methods like resume().
● Considerations:
○ Ensure that the thread can safely continue
execution.
MULTITHREADING IN JAVA

Stopping Threads
● Definition:
○ Forcibly terminating a thread's execution.
● How to Stop:
○ Use methods like stop() (deprecated in some
languages).
● Risks:
○ Can lead to resource leaks or inconsistent state.
MULTITHREADING IN JAVA

Best Practices for Suspending and Resuming


● Avoid Deprecated Methods:
○ Use flags or other mechanisms for control.
● Thread Safety:
○ Ensure data integrity while
suspending/resuming.
● Graceful Suspension:
○ Allow threads to reach safe points before
pausing.
MULTITHREADING IN JAVA

Java Program: Suspending, Resuming, and Stopping Threads


MULTITHREADING IN JAVA

Java Program: Suspending, Resuming, and Stopping Threads


MULTITHREADING IN JAVA

Java Program: Suspending, Resuming, and Stopping Threads


MULTITHREADING IN JAVA

OUTPUT

Thread is running: Thread-0


Thread is running: Thread-0
Thread is running: Thread-0
Suspending thread...
Resuming thread...
Thread is running: Thread-0
Thread is running: Thread-0
Thread is running: Thread-0
Stopping thread...
Thread is stopping: Thread-0
Main thread finished.
JAVA WRAPPING AND UNBOXING

● In Java, wrapper classes are used to convert primitive data types (like
int, char, double, etc.) into corresponding objects.

● Each primitive type has a corresponding wrapper class in the java.lang


package.

● These wrapper classes allow primitives to be treated as objects, which can


be useful in certain contexts, such as working with Java Collections (like
ArrayList, HashMap, etc.), where only objects can be stored.
JAVA WRAPPING AND UNBOXING

Primitive Types and Their Corresponding Wrapper Classes:


● byte -> Byte
● short -> Short
● int -> Integer
● long -> Long
● float -> Float
● double -> Double
● char -> Character
● boolean -> Boolean
JAVA WRAPPING AND UNBOXING
INTEGER CLASS IN JAVA
JAVA WRAPPING AND UNBOXING
INTEGER CLASS IN JAVA
JAVA WRAPPING AND UNBOXING
INTEGER CLASS IN JAVA
JAVA WRAPPING AND UNBOXING

Primitive Types and Their Corresponding Wrapper Classes:


● byte -> Byte
● short -> Short
● int -> Integer
● long -> Long
● float -> Float
● double -> Double
● char -> Character
● boolean -> Boolean
JAVA WRAPPING AND UNBOXING
MULTITHREADING IN JAVA

Boxing or wrapping
MULTITHREADING IN JAVA

Boxing or wrapping

Normal declaration for Integer boxedvalue is auto boxed


MULTITHREADING IN JAVA

Boxing or wrapping

Normal declaration for Integer boxedvalue is auto boxed

Unwrapping value to a variable unwrappedvalue


MULTITHREADING IN JAVA

Without boxedvalue.invalue();, directly boxedvalue is assigned


MULTITHREADING IN JAVA

OUTPUT

Wrapped Value (Manual): 5


Boxed Value (Automatic): 5
Unwrapped Value (Manual): 5
Auto-unboxed Value (Automatic): 5
Sum using Autoboxing and Auto-unboxing: 30

You might also like