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

JAVA PROGRAAMING (314317)- NOTES (UNIT-3)

This document covers exception handling and multithreading in Java, detailing types of errors and exceptions, including checked and unchecked exceptions, and how to handle them using try-catch statements. It explains the use of nested try statements, the throws and throw keywords, and the creation of custom exceptions. Additionally, it introduces multithreading concepts and demonstrates how to create threads by extending the Thread class to improve CPU utilization.
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)
4 views

JAVA PROGRAAMING (314317)- NOTES (UNIT-3)

This document covers exception handling and multithreading in Java, detailing types of errors and exceptions, including checked and unchecked exceptions, and how to handle them using try-catch statements. It explains the use of nested try statements, the throws and throw keywords, and the creation of custom exceptions. Additionally, it introduces multithreading concepts and demonstrates how to create threads by extending the Thread class to improve CPU utilization.
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
You are on page 1/ 21

UNIT-4 EXCEPTION HANDLING & MULTITHREADING

1. TYPES OF ERRORS & EXCEPTIONS


errors and exceptions are both types of throwable objects, but they represent
different types of problems that can occur during the execution of a program.

Errors are usually caused by serious problems that are outside the control of the
program, such as running out of memory or a system crash. Errors are represented by
the Error class and its subclasses. Some common examples of errors in Java include:
 OutOfMemoryError: Thrown when the Java Virtual Machine (JVM) runs out
of memory.
 StackOverflowError: Thrown when the call stack overflows due to too many
method invocations.
 NoClassDefFoundError: Thrown when a required class cannot be found.

Since errors are generally caused by problems that cannot be recovered from,
it’s usually not appropriate for a program to catch errors. Instead, the best course of
action is usually to log the error and exit the program.
Exceptions are used to handle errors that can be recovered from within the
program. Exceptions are represented by the Exception class and its subclasses. Some
common examples of exceptions in Java include:
 NullPointerException: Thrown when a null reference is accessed.
 IllegalArgumentException: Thrown when an illegal argument is passed to a
method.
 IOException: Thrown when an I/O operation fails.

// Java Program to Illustrate Stack overflow error via infinite recursion


class StackOverflow {
public static void test(int i)
{
if (i == 0) return;
else { test(i++); }
}
}
public class Main {
public static void main(String[] args)
{ StackOverflow.test(5); }
}

Exceptions are the conditions that occur at runtime and may cause the
termination of the program. But they are recoverable using try, catch and throw
keywords. Exceptions are divided into two categories:
 Checked exceptions
Checked exceptions are also known as compile-time exceptions as these
exceptions are checked by the compiler during the compilation process to
confirm whether the exception is handled by the programmer or not. If
not, then the system displays a compilation error.
For
example, SQLException, IOException, InvocationTargetException, a
nd ClassNotFoundException.
 Unchecked exceptions
The unchecked exceptions are those exceptions that occur during the
execution of the program. Hence they are also referred to as Runtime
exceptions. These exceptions are generally ignored during the
compilation process. They are not checked while compiling the program.
For example, programming bugs like logical errors, and using incorrect
APIs
Checked exceptions like IOException known to the compiler at compile time
while unchecked exceptions like ArrayIndexOutOfBoundException known to the
compiler at runtime. It is mostly caused by the program written by the programmer.
Errors Exceptions

We can recover from exceptions by either using


Recovering from Error is not possible. try-catch block or throwing exceptions back to
the caller.

Exceptions include both checked as well as


All errors in java are unchecked type.
unchecked type.

Errors are mostly caused by the


Program itself is responsible for causing
environment in which program is
exceptions.
running.

Errors can occur at compile time as


well as run time. Compile Time: eg All exceptions occurs at runtime but checked
Syntax Error exceptions are known to the compiler while
unchecked are not.
Run Time: Logical Error.

They are defined in java.lang.Error


They are defined in java.lang.Exception package
package.

Examples : Checked Exceptions : SQLException,


Examples :
IOException Unchecked Exceptions :
java.lang.StackOverflowError,
ArrayIndexOutOfBoundException,
java.lang.OutOfMemoryError
NullPointerException, ArithmeticException.

2. TRY & CATCH STATEMENT


The try...catch block in Java is used to handle exceptions and prevents the
abnormal termination of the program.
Syntax:
try { // code }catch(exception e) { // code }

The try block includes the code that might generate an exception.
The catch block includes the code that is executed when there occurs an
exception inside the try block.
class TryDemo {
public static void main(String[] args) { ArithmeticException
try { => / by zero
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => "
+e.getMessage());
}
}}

try...finally block

We can also use the try block along with a finally block.

In this case, the finally block is always executed whether there is an exception

inside the try block or not.

class Main {
public static void main(String[] args) { Finally block is always
try { executed
int divideByZero = 5 / 0; Exception in thread "main"
} java.lang.ArithmeticException:
finally { / by zero at
System.out.println("Finally block is always Main.main(Main.java:4)
executed");
}
}
}

try...catch...finally block

we can also use the finally block after the try...catch block.
import java.io.*;
class ListOfNumbers { Entering try statement
private int[] list = {5, 6, 8, 9, 2}; Exception => Index 5 out of
public void writeList() { bounds for length 5
PrintWriter out = null; Closing PrintWriter
try {
System.out.println("Entering try statement");
out = new PrintWriter(new
FileWriter("OutputFile.txt"));
for (int i = 0; i < 7; i++)
{ out.println("Value at: " + i + " = " +
list[i]); }
}
catch (Exception e)
{ System.out.println("Exception => " +
e.getMessage()); }
finally {
if (out != null)
{ System.out.println("Closing
PrintWriter");
out.close();
}
else
{ System.out.println("PrintWriter not
open"); }
} }}
class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
list.writeList();
}
}

3. NESTED TRY STATEMENTS


Using a try block inside another try block is permitted. It is called as nested try
block.
For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).
Sometimes a situation may arise where a part of a block may cause one error
and the entire block itself may cause another error. In such cases, exception
handlers have to be nested.

public class NestedTryBlock{


public static void main(String args[]){
try{
try{
System.out.println("going to divide by 0");
int b =39/0;
} catch(ArithmeticException e) { System.out.println(e); }
try{
int a[]=new int[5];
a[5]=4;

}catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); }
System.out.println("other statement");
//catch block of outer try block

catch(Exception e) { System.out.println("handled the exception (outer catch)"); }


System.out.println("normal flow..");
}

4. THROWS & THROW STATEMENTS


We use the throws keyword in the method declaration to declare the type of
exceptions that might occur within it.

import java.io.*;
class Main { java.io.FileNotFoundException:
public static void findFile() throws IOException { test.txt (No such file or
File newFile=new File("test.txt"); directory)
FileInputStream stream=new
FileInputStream(newFile);
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e) {
System.out.println(e); }
}
}
Throwing multiple exceptions

import java.io.*;
class Main {
public static void findFile() throws NullPointerException, IOException,
InvalidClassException {
// code that may produce NullPointerException
………
// code that may produce IOException
………
// code that may produce InvalidClassException
………
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e1)
{ System.out.println(e1.getMessage()); } catch(InvalidClassException e2)
{ System.out.println(e2.getMessage()); }
}

Java throw keyword

The throw keyword is used to explicitly throw a single exception.


When an exception is thrown, the flow of program execution transfers from the try block

to the catch block. We use the throw keyword within a method.

class Main {
public static void divideByZero() { Exception in thread "main"
throw new ArithmeticException("Trying to java.lang.ArithmeticException:
divide by 0"); Trying to divide by 0
} at
public static void main(String[] args) Main.divideByZero(Main.java:3)
{ divideByZero(); } at Main.main(Main.java:7)
} exit status 1
Throwing checked exception File not found
import java.io.*;
class Main {
public static void findFile() throws IOException {
throw new IOException("File not found");
}
public static void main(String[] args) {
try {
findFile();
System.out.println("Rest of code in try
block");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}

5. BUILT-IN EXCEPTIONS
The Java programming language has several built-in exception class that
support exception handling. All the built-in exception classes in Java were defined a
package java.lang.
S.
No. Checked Exception Class with Description

1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a
particular class and the specified class cannot be found in the
classpath.

2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been
called to clone an object, but that the object's class does not
implement the Cloneable interface.

3 InstantiationException
It is thrown when an application tries to create an instance of a class
using the newInstance method in class Class , but the specified class
object cannot be instantiated because it is an interface or is an
abstract class.

4 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is
interrupted.
S.
No. Checked Exception Class with Description

5 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime
that it had at compile time, a NoSuchMethodException occurs during
reflection when we try to access a method that does not exist.

Unchecked Exception Class with Description

1. ArithmeticException It handles the arithmetic exceptions like dividion by


zero
2. ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index.
The index is either negative or greater than or equal to the size of the array.
3. ArrayStoreException
It handles the situations like when an attempt has been made to store the
wrong type of object into an array of objects
4. ClassCastException It handles the situation when we try to improperly cast a
class from one type to another.
5. IllegalArgumentException This exception is thrown in order to indicate that a
method has been passed an illegal or inappropriate argument.
IllegalStateException It signals that a method has been invoked at an illegal or
inappropriate time.
6. IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to
modify the state of the thread when it is illegal.
7. IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an
array , vector , string , and so forth.
8. NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.
9. NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
10. NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or
integer, but the format of the input string is not appropriate or illegal.
11. StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is
either negative, or greater than the size of the string itself.
6. CHAINED EXCEPTIONS
Chained Exceptions allows to relate one exception with another
exception, i.e one exception describes cause of another exception.
For example, consider a situation in which a method throws an
ArithmeticException because of an attempt to divide by zero but the actual
cause of exception was an I/O error which caused the divisor to be zero.
The method will throw only ArithmeticException to the caller. So the
caller would not come to know about the actual cause of exception. Chained
Exception is used in such type of situations.
// Java program to demonstrate working of chained exceptions
public class ExceptionHandling
{
public static void main(String[] args)
{
try{
NumberFormatException ex = new NumberFormatException("Exception");
ex.initCause(new NullPointerException( "This is actual cause of the
exception"));
throw ex;
}catch(NumberFormatException ex) {
System.out.println(ex);
System.out.println(ex.getCause());
}
}
}
Output:
java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is actual cause of the exception

getCause():- This method returns actual cause of an exception.


initCause(Throwable cause) :- This method sets the cause for the calling
exception.

7. CREATING OWN EXCEPTIONS (THROW CLAUSE)


Java provides us the facility to create our own exceptions which are basically
derived classes of Exception.
Creating our own Exception is known as a custom exception or user-defined
exception. Basically, Java custom exceptions are used to customize the exception
according to user needs.
In simple words, we can say that a User-Defined Exception or custom
exception is creating your own exception class and throwing that exception using the
‘throw’ keyword.
class InvalidAgeException extends Exception {
public InvalidAgeException (String str)
{ super(str); }
}
public class TestCustomException1 {
static void validate (int age) throws InvalidAgeException{
if(age < 18)
{ throw new InvalidAgeException("age is not valid to vote"); }
else { System.out.println("welcome to vote"); }
}
public static void main(String args[]) {
try { validate(13); }
catch (InvalidAgeException ex)
{ System.out.println("Caught the exception");
// printing the message from InvalidAgeException object
System.out.println("Exception occured: " + ex);
}
System.out.println("rest of the code...");
}
}

8. CREATING THREAD BY EXTENDING TO THREAD CLASS


Used to maximize the CPU utilization.
We don't want our CPU to be in a free state; for example, Func1() comes into
the memory and demands any input/output process. The CPU will need to wait for
unit Func1() to complete its input/output operation in such a condition. But, while
Func1() completes its I/O operation, the CPU is free and not executing any thread.
So, the efficiency of the CPU is decreased in the absence of multithreading.
class Multi extends Thread{
class ThreadExample{ public void run(){
public static void main(String[] args) System.out.println("thread is
{ running...");
Func1(); }
Func2(); public static void main(String
} args[]){
} Multi func1=new Multi();
func1.start();
Multi func2=new Multi();
func2.start();
********************************* }
In the above code, we can see that }
Func1() and Func2() are called inside the ***************************
main() function. But the execution of Func1() and Func2() are called inside
Func2() will start only after the the main function, but none of the
completion of the Func1(). two functions is waiting for the
execution of the other function. Both
the functions are getting executed
concurrently.
To create a thread using the thread class, we need to extend the thread class.
The code you want to execute on the thread's execution goes inside the run()
method.
class MyThread extends Thread{
public void run(){
int i =0;
while(i<40000){
System.out.println("My Cooking Thread is Running");
System.out.println("I am happy!");
i++;
}
}
}
public class cwh_70 {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}

In order to execute the thread, the start() method is used. start() is called on
the object of the MyThread class. It automatically calls the run() method.

9. CREATING THREAD BY IMPLELENTING RUNNABLE INTERFACE


Steps To Create A Java Thread Using Runnable Interface:
 Create a class and implement the Runnable interface by using
the implements keyword.
 Override the run() method inside the implementer class.
 Create an object of the implementer class in the main() method.
 Instantiate the Thread class and pass the object to the Thread constructor.
 Call start() on the thread. start()will call the run()method.
classs t1 implements Runnable
{
public void run()
{ System.out.println("Thread is running"); }
}
public class ClassName{
public static void main(String[] args) {
t1 obj1 = new t1();
Thread t = new Thread(obj1);
t.start();
}
}
Runnable Interface Vs Extending Thread Class
The Runnable interface is preferred over extending the Thread class because of
the following reasons:
 As multiple inheritance is not supported in Java, it is impossible to extend
the Thread class if your class had already extended some other class.
 While implementing Runnable, we do not modify or change the thread's
behavior.
 More memory is required while extending the Thread class because each
thread creates a unique object.
 Less memory is required while implementing Runnable because multiple
threads share the same object.

10. LIFE CYCLE OF THREAD


Basically state transitions of a thread that starts from its birth and ends on its
death.
When an instance of a thread is created and is executed by calling start()
method of Thread class, the thread goes into runnable state.
When sleep() or wait() method is called by Thread class, the thread enters into
non-runnable state.
From non-runnable state, thread comes back to runnable state and continues
execution of statements.
When the thread comes out of run() method, it dies. These state transitions of a
thread are called Thread life cycle in Java..

A thread is a path of execution in a program that enters any one of the following
five states during its life cycle. The five states are as follows:
1. New
When we create a thread object using Thread class, thread is born and is
known to be in Newborn state. That is, when a thread is born, it enters into
new state but the start() method has not been called yet on the instance.
Thread object exists but it cannot execute any statement because it is not
an execution of thread. Only start() method can be called on a new thread;
otherwise, an IllegalThreadStateException will be thrown.
2. Runnable
Runnable state means a thread is ready for execution. When the start()
method is called on a new thread, thread enters into a runnable state.
In runnable state, thread is ready for execution and is waiting for
availability of the processor (CPU time).
If all threads have equal priority, CPU allocates time slots for thread
execution on the basis of first-come, first-serve manner. The process of
allocating time to threads is known as time slicing.
3. Running
Running means Processor (CPU) has allocated time slot to thread for its
execution. When thread scheduler selects a thread from the runnable state
for execution, it goes into running state.
In running state, processor gives its time to the thread for execution and
executes its run method. This is the state where thread performs its actual
functions. A thread can come into running state only from runnable state.
4. Blocked (Non-runnable state)
A thread is considered to be in the blocked state when it is suspended,
sleeping, or waiting for some time in order to satisfy some condition.
5. Dead
A thread dies or moves into dead state automatically when its run() method
completes the execution of statements. That is, a thread is terminated or
dead when a thread comes out of run() method. A thread can also be dead
when the stop() method is called.
11. THREAD EXCEPTIONS
When we call a sleep() method in a Java program, it must be enclosed in
try block and followed by catch block.
This is because sleep() method throws an exception named
InterruptedException that should be caught. If we fail to catch this exception,
the program will not compile.
For example, a thread that is in a sleeping state cannot deal with the
resume() method because a sleeping thread cannot accept instructions. The
same thing is true for the suspend() method when it is used on a blocked
thread.
12. THREAD PRIORITY & METHODS
 A thread's priority is an integer in the range 1 to 10.
 The larger the integer, the higher the priority.
 The thread scheduler uses this integer from each thread to determine which
one should be allowed to execute.

 Minimum priority
 Normal priority
 Maximum priority

The Thread class defines these priority types as


constants MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY, with values 1,
5, and 10, respectively. NORM_PRIORITY is the default priority for a
new Thread.
 The setPriority() method of thread class is used to change the thread's
priority.
 The getPriority() instance method returns the integer that represents its
priority.
public class JavaSetPriorityExp1 extends Thread{
public void run()
{ System.out.println("Priority of thread is: "+Thread.currentThread().g
etPriority()); } public static void main(String args[]) {
JavaSetPriorityExp1 t1=new JavaSetPriorityExp1();
t1.setPriority(Thread.MAX_PRIORITY);
t1.start();
}
}
Output: Priority of thread is: 10

public class JavaSetPriority extends Thread {


public void run() { System.out.println("running..."); }
public static void main(String args[]) {
JavaSetPriority t1=new JavaSetPriority();
JavaSetPriority t2=new JavaSetPriority();
t1.setPriority(4);
t2.setPriority(7);
System.out.println("Priority of thread t1 is: " + t1.getPriority()); //4
System.out.println("Priority of thread t2 is: " + t2.getPriority()); //7
t1.start();
}
}

13. SYNCHRONIZATIONS
Synchronization in java is the capability to control the access of multiple threads
to any shared resource.
In the Multithreading concept, multiple threads try to access the shared
resources at a time to produce inconsistent results.
The synchronization is necessary for reliable communication between threads.
 Synchronization helps in preventing thread interference.
 Synchronization helps to prevent concurrency problems.
Synchronization is classified into two types
 Process Synchronization
The process is nothing but a program under execution. It runs
independently isolated from another process. The resources like memory and
CPU time, etc. are allocated to the process by the operation System.
 Thread Synchronization
Thread synchronization is two types, they are:
1. Mutual Exclusive:
A Mutex or Mutual Exclusive helps only one thread to access the
shared resources. It won’t allow the accessing of shared resources at a
time. It can be achieved in the following ways.
1. Synchronized Method
If we use the Synchronized keywords in any method then
that method is Synchronized Method.
 It is used to lock an object for any shared resources.
 The object gets the lock when the synchronized method is called.
 The lock won’t be released until the thread completes its function.

CLASS POWER{

SYNCHRONIZED VOID PRINTPOWER(INT N){

INT TEMP = 1; FOR(INT I=1;I<=5;I++){


SYSTEM.OUT.PRINTLN(THREAD.CURRENTTHREAD().GETNAME() + ":- " +N +
"^"+ I + " VALUE: " + N*TEMP);
TEMP = N*TEMP;
TRY{

THREAD.SLEEP(500);

}CATCH(EXCEPTION E){SYSTEM.OUT.PRINTLN(E); }
}
}
}
CLASS THREAD1 EXTENDS THREAD{

POWER P;

THREAD1(POWER P){ THIS.P=P; }


PUBLIC VOID RUN(){ P.PRINTPOWER(5); }
}
CLASS THREAD2 EXTENDS THREAD{

POWER P;

THREAD2(POWER P) { THIS.P=P; }
PUBLIC VOID RUN() { P.PRINTPOWER(8); }
}
PUBLIC CLASS SYNCHRONIZATION_EXAMPLE2 {
PUBLIC STATIC VOID MAIN(STRING ARGS[]){

POWER OBJ = NEW POWER();


THREAD1 P1=NEW THREAD1(OBJ);

THREAD2 P2=NEW THREAD2(OBJ);

P1.START();

P2.START();

}
}

2. Synchronized block
Suppose you don’t want to synchronize the entire method, you want to
synchronize few lines of code in the method, then a synchronized block helps to
synchronize those few lines of code. It will take the object as a parameter. It
will work the same as Synchronized Method. In the case of synchronized
method lock accessed is on the method but in the case of synchronized block
lock accessed is on the object.

CLASS POWER{
VOID PRINTPOWER(INT N){

SYNCHRONIZED(THIS){

INT TEMP = 1;
FOR(INT I=1;I<=5;I++){

SYSTEM.OUT.PRINTLN(THREAD.CURRENTTHREAD().GETNAME() + ":- " +N + "^"+ I


+ " VALUE: " + N*TEMP);
TEMP = N*TEMP;
TRY{ THREAD.SLEEP(500);

}CATCH(EXCEPTION E){SYSTEM.OUT.PRINTLN(E);}
}
}
}
} CLASS THREAD1 EXTENDS THREAD{
POWER P;
THREAD1(POWER P){ THIS.P=P; }
PUBLIC VOID RUN(){ P.PRINTPOWER(5); }

} CLASS THREAD2 EXTENDS THREAD{


POWER P;
THREAD2(POWER P){ THIS.P=P; }
PUBLIC VOID RUN(){ P.PRINTPOWER(8); }
} PUBLIC CLASS SYNCHRONIZATION_EXAMPLE3{
PUBLIC STATIC VOID MAIN(STRING ARGS[]){

POWER OBJ = NEW POWER();//ONLY ONE OBJECT


THREAD1 P1=NEW THREAD1(OBJ);
THREAD2 P2=NEW THREAD2(OBJ);
P1.START();

P2.START();

}
}

Static Synchronization
In java, every object has a single lock (monitor) associated with it. The
thread which is entering into synchronized method or synchronized block will get
that lock, all other threads which are remaining to use the shared resources
have to wait for the completion of the first thread and release of the lock.
Suppose in the case of where we have more than one object, in this case,
two separate threads will acquire the locks and enter into a synchronized block
or synchronized method with a separate lock for each object at the same time.
To avoid this, we will use static synchronization.
In this, we will place synchronized keywords before the static method. In
static synchronization, lock access is on the class not on object and Method.

2. Cooperation (Inter Thread Communication in java)

14. INTER-THREAD COMMUNICATION


a technique through which multiple threads communicate with each other.
It provides an efficient way through which more than one thread
communicates with each other by reducing CPU idle time. CPU idle time is a
process in which CPU cycles are not wasted.
When more than one threads are executing simultaneously, sometimes
they need to communicate with each other by exchanging information with each
other. A thread exchanges information before or after it changes its state.
For example, suppose that there are two threads A and B. Thread B uses
data produced by Thread A and performs its task.
If Thread B waits for Thread A to produce data, it will waste many CPU
cycles. But if threads A and B communicate with each other when they have
completed their tasks, they do not have to wait and check each other’s status
every time.
Thus, CPU cycles will not waste. This type of information exchanging
between threads is called inter-thread communication in Java.
Inter thread communication in Java can be achieved by using three methods
provided by Object class of java.lang package. They are:
1. wait()
2. notify()
3. notifyAll()
These methods can be called only from within a synchronized method or
synchronized block of code otherwise, an exception
named IllegalMonitorStateException is thrown.
***All these methods are declared as final. Since it throws a checked
exception, therefore, you must be used these methods within Java try-catch
block
wait()
wait() method in Java notifies the current thread to give up the monitor
(lock) and to go into sleep state until another thread wakes it up by calling
notify() method.
This method throws InterruptedException.
Syntax: public final void wait()
public final void wait(long millisecond) throws InterruptedException
notify()
The notify() method wakes up a single thread that called wait() method
on the same object.
If more than one thread is waiting, this method will awake one of them.
Syntax: public final void notify()
notifyAll()
The notifyAll() method is used to wake up all threads that called wait()
method on the same object. The thread having the highest priority will run first.
Syntax: public final void notifyAll()
Producer-Consumer Problem in Java using wait and notify methods
 Q where we will try to synchronize data.
 Producer where Producer thread will produce data (or some goods).
 Consumer where Consumer thread will wait for Producer to produce data.
When the Producer thread completes the production of data, the Consumer
thread will take that data and use it.

15. DEADLOCK
Deadlock in java is a programming situation where two or more threads
are blocked forever. Java deadlock situation arises with at least two threads and
two or more resources.
Deadlock describes a situation where two or more threads are blocked
forever, waiting for each other. Deadlock occurs when multiple threads need the
same locks but obtain them in different order.
A Java multithreaded program may suffer from the deadlock condition
because the synchronized keyword causes the executing thread to block while
waiting for the lock, or monitor, associated with the specified object.
public class TestThread
{
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();

public static void main(String args[]) {


ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
T2.start();
}
private static class ThreadDemo1 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 1: Holding lock 1...");
try { Thread.sleep(10); } catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) { System.out.println("Thread 1: Holding lock 1 &
2..."); } } } }
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock2) { System.out.println("Thread 2: Holding lock 2...");
try { Thread.sleep(10); } catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) { System.out.println("Thread 2: Holding lock 1&2...");
} } } } }
Thread 1: Holding lock 1...
Thread 2: Holding lock 2...
Thread 2: Waiting for lock 1...
Thread 1: Waiting for lock 2...
Deadlock Solution
public class TestThread {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[]) {
ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
T2.start();
}
private static class ThreadDemo1 extends Thread {
public void run() {
synchronized (Lock1) { System.out.println("Thread 1: Holding lock 1...");
try { Thread.sleep(10); }catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) { System.out.println("Thread 1: Holding lock 1 & 2...");
} } } }
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1...");
try { Thread.sleep(10); } catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 2...");
synchronized (Lock2) { ystem.out.println("Thread 2: Holding lock 1 & 2...");
} } } } }
Thread 1: Holding lock 1...
Thread 1: Waiting for lock 2...
Thread 1: Holding lock 1 & 2...
Thread 2: Holding lock 1...
Thread 2: Waiting for lock 2...
Thread 2: Holding lock 1 & 2...

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy