0% found this document useful (0 votes)
9 views98 pages

Unit III - OOPs - Updated On 4.1.24 (Reg 21)

Uploaded by

mrsktrader25
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)
9 views98 pages

Unit III - OOPs - Updated On 4.1.24 (Reg 21)

Uploaded by

mrsktrader25
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/ 98

CS3391 – Object Oriented

Programming
Unit III – Exception Handling and Multi
Threading
By

D. Durai kumar,
Head of the Department
Department of Information Technology
Ganadipathy Tulsi’s Jain Engineering College
Vellore

By D. Durai kumar, HOD / IT


3.1 Exceptions
Difference between error and exception
Error
 Errors indicate serious problems and abnormal
conditions that most applications should not try to
handle.
 Error defines problems that are not expected to be caught
under normal circumstances by our program.
 For example memory error, hardware error, JVM error
etc.

By D. Durai kumar, HOD / IT


3.1 Exceptions
Difference between error and exception
Exceptions
 Exceptions are conditions within the code.
 A developer can handle such conditions and take
necessary corrective actions.
 Few examples
– DivideByZero exception
– NullPointerException
– ArithmeticException
– ArrayIndexOutOfBoundsException

By D. Durai kumar, HOD / IT


3.1 Exceptions
Exceptions
 An exception (or exceptional event) is a problem that
arises during the execution of a program.
 When an Exception occurs the normal flow of the
program is disrupted and the program/Application
terminates abnormally, which is not recommended,
therefore, these exceptions are to be handled.
 If an exception is raised, which has not been handled by
programmer then program execution can get terminated
and system prints a non user friendly error message.

By D. Durai kumar, HOD / IT


3.1 Exceptions
Example:
 Exception in thread "main"
java.lang.ArithmeticException: / by zero at
ExceptionDemo.main(ExceptionDemo.java:5)

Where,
ExceptionDemo : The class name
main : The method name
 ExceptionDemo.java : The filename
 java:5 : Line number

By D. Durai kumar, HOD / IT


3.1 Exceptions
Example:
 An exception can occur for many different reasons.

Following are some scenarios where an exception occurs.

A user has entered an invalid data.


A file that needs to be opened cannot be found.
A network connection has been lost in the middle of
communications or the JVM has run out of memory.

By D. Durai kumar, HOD / IT


3.2 Exception Hierarchy
 All exception classes are subtypes of the
java.lang.Exception class.
 The exception class is a subclass of the Throwable class.

By D. Durai kumar, HOD / IT


3.2 Exception Hierarchy
Key words used in Exception handling
 There are 5 keywords used in java exception handling.

By D. Durai kumar, HOD / IT


3.2 Exception Hierarchy
Key words used in Exception handling
 There are 5 keywords used in java exception handling:
try, catch, throw, throws, and finally.
1. try block :
 Program statements that you want to monitor for
exceptions are contained within a try block.
 If an exception occurs within the try block, it is thrown.

2. catch block:
 Your code can catch the exception using catch and
handle it in some rational manner.
 System-generated exceptions are automatically thrown
by the Java runtime system.
By D. Durai kumar, HOD / IT
3.2 Exception Hierarchy
Key words used in Exception handling
3. throw:
 To manually throw an exception, use the keyword throw.
4. throws:
 Any exception that is thrown out of a method must be
specified as such by a throws clause.
5. finally:
 Any code that absolutely must be executed before a
method returns is put in a finally block

By D. Durai kumar, HOD / IT


3.2 Exception Hierarchy
 This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// ...
finally
{
// block of code to be executed before try block ends
} By D. Durai kumar, HOD / IT
3.2 Exception Hierarchy
 This is the general form of an exception-handling block:

By D. Durai kumar, HOD / IT


3.3 Exception Types
 All exception types are subclasses of the built-in class
Throwable.
 Immediately below Throwable are two subclasses
1. Exception.
2. Error
 Exception: This class is used for exceptional conditions
that user programs should catch. This is also the class
that you will subclass to create your own custom
exception types.

 RuntimeException: There is an important subclass of


Exception.
 Exceptions of this type are automatically defined for the
programs that you write and include things such as
division by zero and invalid array indexing.
By D. Durai kumar, HOD / IT
3.3 Exception Types
Error:
 Error, which defines exceptions that are not expected to
be caught under normal circumstances by your program.
 Exceptions of type Error are used by the Java run-time
system to indicate errors having to do with the run-time
environment, itself.
 Ex : Stack overflow

By D. Durai kumar, HOD / IT


3.3 Exception Types
Uncaught Exceptions
 It is useful to see what happens when you don't handle
them.
Ex: This small program includes an expression that
intentionally causes a divide-by-zero error.
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}

By D. Durai kumar, HOD / IT


3.3 Exception Types
Uncaught Exceptions
 When the Java run-time system detects the attempt to
divide by zero, it constructs a new exception object and
then throws this exception.
 This causes the execution of Exc0 to stop.
 Once an exception has been thrown, it must be caught by
an exception handler and dealt with immediately.
 In this example, we haven't supplied any exception
handlers of our own, so the exception is caught by the
default handler provided by the Java run-time system.
 Default handler: Any exception that is not caught by
your program will ultimately be processed by the default
handler.
 The default handler displays a string describing the
exception, prints a stack trace from the point at which the
exception occurredBy D. Durai kumar, HOD / IT
3.3 Exception Types
Uncaught Exceptions
 java.lang.ArithmeticException: / by zero at
Exc0.main(Exc0.java:4)

 The type of the exception thrown is a subclass of


Exception called ArithmeticException.
 describes what type of error happened.
 The stack trace will always show the sequence of method
invocations that led up to the error.

By D. Durai kumar, HOD / IT


3.3 Exception Types

By D. Durai kumar, HOD / IT


3.3 Exception Types
Stack Trace:
 Stack Trace is a list of method calls from the point when
the application was started to the point where the
exception was thrown.
 The most recent method calls are at the top.
 A stacktrace is a very helpful debugging tool.
 It is a list of the method calls that the application was in
the middle of when an Exception was thrown.
 This is very useful because it doesn't only show you
where the error happened, but also how the program
ended up in that place of the code..

By D. Durai kumar, HOD / IT


Using try and catch
Using try and Catch
 To guard against and handle a run-time error, simply
enclose the code that you want to monitor inside a try
block.
 Immediately following the try block, include a catch
clause that specifies the exception type that you wish to
catch.
 A try and its catch statement form a unit.

By D. Durai kumar, HOD / IT


Using try and catch
Using try and Catch

The call to println( ) inside the try block is never executed.


By D. Durai kumar, HOD / IT
Multiple catch clauses
Multiple catch Clauses
 In some cases, more than one exception could be raised
by a single piece of code.
 To handle this type of situation, you can specify two or
more catch clauses, each catching a different type of
exception.
 When an exception is thrown, each catch statement is
inspected in order.
 The first one whose type matches that of the exception is
executed.
 After one catch statement executes, the others are
bypassed, and execution continues after the try/catch
block.

By D. Durai kumar, HOD / IT


Multiple catch clauses
Multiple catch Clauses

By D. Durai kumar, HOD / IT


Nested try Statements
Nested try Statements
 The try statement can be nested.
 That is, a try statement can be inside the block of another
try.
 Each time a try statement is entered, the context of that
exception is pushed on the stack.
 If an inner try statement does not have a catch handler for
a particular exception, the stack is unwound and the next
try statement’s catch handlers are inspected for a match.
 This continues until one of the catch statements succeeds,
or until all of the nested try statements are exhausted.
 If no catch statement matches, then the Java run-time
system will handle the exception.

By D. Durai kumar, HOD / IT


Nested try Statements

By D. Durai kumar, HOD / IT


Nested try Statements

By D. Durai kumar, HOD / IT


throw
throw
 it is possible for your program to throw an exception
explicitly, using the throw statement.
 The general form of throw is shown here:
throw ThrowableInstance;
 Here, ThrowableInstance must be an object of type
Throwable or a subclass of Throwable.
 Primitive types, such as int or char, as well as non-
Throwable classes, such as String and Object, cannot be
used as exceptions.
 There are two ways you can obtain a Throwable object:
1. using a parameter in a catch clause, or
2. creating one with the new operator.

By D. Durai kumar, HOD / IT


throw
throw
 The flow of execution stops immediately after the throw
statement; any subsequent statements are not executed.
 The nearest enclosing try block is inspected to see if it
has a catch statement that matches the type of exception.
 If it does find a match, control is transferred to that
statement.
 If not, then the next enclosing try statement is inspected,
and so on.
 If no matching catch is found, then the default exception
handler halts the program and prints the stack trace

By D. Durai kumar, HOD / IT


throw
Throw

By D. Durai kumar, HOD / IT


throws
throws
 If a method is capable of causing an exception that it
does not handle, it must specify this behaviour so that
callers of the method can guard themselves against that
exception.
 We do this by including a throws clause in the method’s
declaration.
 A throws clause lists the types of exceptions that a
method might throw.
 This is necessary for all exceptions, except those of type
Error or RuntimeException, or any of their subclasses.
 All other exceptions that a method can throw must be
declared in the throws clause

By D. Durai kumar, HOD / IT


throws
throws
 This is the general form of a method declaration that
includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}

 Here, exception-list is a comma-separated list of the


exceptions that a method can throw

By D. Durai kumar, HOD / IT


throws
Throws

By D. Durai kumar, HOD / IT


finally
finally
 The finally keyword is designed to address this
contingency.
 finally creates a block of code that will be executed after
a try/catch block has completed and before the code
following the try/catch block.
 The finally block will execute whether or not an
exception is thrown.
 If an exception is thrown, the finally block will execute
even if no catch statement matches the exception.
 Any time a method is about to return to the caller from
inside a try/catch block, via an uncaught exception or an
explicit return statement, the finally clause is also
executed just before the method returns.
By D. Durai kumar, HOD / IT
finally
Finally

By D. Durai kumar, HOD / IT


finally
Finally

By D. Durai kumar, HOD / IT


finally
Finally

By D. Durai kumar, HOD / IT


Categories of Exceptions
Categories of Exceptions
 Checked exceptions (Compile Time Exception)
– A checked exception is an exception that occurs at the
compile time.
– These exceptions cannot simply be ignored at the time of
compilation, the programmer should take care of (handle)
these exceptions.
 Unchecked exceptions (Runtime Exception)
– An unchecked exception is an exception that occurs at the
time of execution.
– These include programming bugs, such as logic errors or
improper use of an API.
– Runtime exceptions are ignored at the time of compilation.

By D. Durai kumar, HOD / IT


Common scenarios where exception may
occur
Common scenarios where exceptions may occur:
 There are given some scenarios where unchecked
exceptions can occur. They are as follows:
1) Scenario where ArithmeticException occurs
 If we divide any number by zero, there occurs an
ArithmeticException.
 int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs .


 If we have null value in any variable, performing any
operation by the variable occurs an
NullPointerException.
 String s=null;
 System.out.println(s.length());//NullPointerException
By D. Durai kumar, HOD / IT
Common scenarios where exception may
occur
Common scenarios where exceptions may occur:
3. Scenario where ArrayIndexOutOfBoundsException
occurs
 If you are inserting any value in the wrong index, it
would result
 ArrayIndexOutOfBoundsException as shown below:
 int a[]=new int[5];
 a[10]=50; //ArrayIndexOutOfBoundsException

By D. Durai kumar, HOD / IT


java Built in Exceptions
Java’s Built-in Exceptions
 Inside the standard package java.lang, Java defines
several exception classes.
 The most general of these exceptions are subclasses of
the standard type RuntimeException.
 Since java.lang is implicitly imported into all Java
programs, most exceptions derived from
RuntimeException are automatically available.
 Furthermore, they need not be included in any method's
throws list.
 In the language of Java, these are called unchecked
exceptions because the compiler does not check to see if
a method handles or throws these exceptions

By D. Durai kumar, HOD / IT


Java's Unchecked RuntimeException Subclasses

By D. Durai kumar, HOD / IT


Java's Unchecked Runtime Exception Subclasses

By D. Durai kumar, HOD / IT


java Built in Exceptions
Java’s Built-in Exceptions
 Exceptions defined by java.lang that must be included in
a method's throws list if that method can generate one of
these exceptions and does not handle it itself. These are
called checked exceptions

By D. Durai kumar, HOD / IT


Java's checked Runtime Exception Subclasses

By D. Durai kumar, HOD / IT


Creating own exceptions
Creating Your Own Exception Subclasses
 Although Java's built-in exceptions handle most common
errors, you will probably want to create your own
exception types to handle situations specific to your
applications.
 This is quite easy to do: just define a subclass of
Exception (which is, of course, a subclass of Throwable).
 Your subclasses don't need to actually implement
anything—it is their existence in the type system that
allows you to use them as exceptions.
 The Exception class does not define any methods of its
own.
 It does, of course, inherit those methods provided by
Throwable.
By D. Durai kumar, HOD / IT
Creating own exceptions
Creating Your Own Exception Subclasses
 Thus, all exceptions, including those that we create, have
the methods defined by Throwable available to them

By D. Durai kumar, HOD / IT


Creating own exceptions
The Methods by Throwable

By D. Durai kumar, HOD / IT


java Built in Exceptions
Java’s Built-in Exceptions
 User-defined Exceptions
– All exceptions must be a child of Throwable.
– If we want to write a checked exception that is
automatically enforced by the Handle ,we need to
extend the Exception class.
– User defined exception needs to inherit (extends)
Exception class in order to act as an exception.
– throw keyword is used to throw such exceptions.

By D. Durai kumar, HOD / IT


Creating own exceptions
 User-defined Exceptions

By D. Durai kumar, HOD / IT


Advantages of Exception Handling
Advantages of Exception Handling
 Exception handling allows us to control the normal flow
of the program by using exception handling in program.
 It throws an exception whenever a calling method
encounters an error providing that the calling method
takes care of that error.
 It also gives us the scope of organizing and
differentiating between different error types using a
separate block of codes. This is done with the help of try-
catch blocks.

By D. Durai kumar, HOD / IT


4.1 Differences between Multithreading
and Multitasking
Process
 Program in execution is called as process.
 Heavy weight process

Thread:
 A thread is a single sequential (separate) flow of control
within program.
 Sometimes, it is called an execution context or light
weight process.

By D. Durai kumar, HOD / IT


4.1 Differences between Multithreading
and Multitasking
Multithreading
 Multithreading is a conceptual programming concept
where a program (process) is divided into two or more
subprograms (process), which can be implemented at the
same time in parallel.
 A multithreaded program contains two or more parts that
can run concurrently.
 Each part of such a program is called a thread, and each
thread defines a separate path of execution.

By D. Durai kumar, HOD / IT


4.1 Differences between Multithreading
and Multitasking
Multitasking
 Executing several tasks simultaneously is called multi-
tasking.
 There are 2 types of multi-tasking
– 1. Process-based multitasking
– 2. Thread-based multi-tasking
1. Process-based multi-tasking
 Executing various jobs together where each job is a
separate independent operation is called process-based
multi-tasking.
2. Thread-based multi-tasking
 Executing several tasks simultaneously where each task
is a separate independent part of the same program is
called Thread-based multitasking.
By D. Durai kumar, HOD / IT
4.1 Differences between Multithreading
and Multitasking
Multitasking
2. Thread-based multi-tasking (contd.,)
 Each independent part is called Thread.
 It is best suitable for the programmatic level.
 The main goal of multi-tasking is to make or do a better
performance of the system by reducing response time

By D. Durai kumar, HOD / IT


4.1 Differences between Multithreading
and Multitasking

By D. Durai kumar, HOD / IT


4.2 Thread Life Cycle
Life Cycle of Thread
A thread can be in any of the five following states
 1. Newborn
 2. Runnable
 3. Running
 4. Blocked
 5. Dead

By D. Durai kumar, HOD / IT


4.2 Thread Life Cycle
Life Cycle of Thread
A thread can be in any of the five following states

By D. Durai kumar, HOD / IT


4.2 Thread Life Cycle
Life Cycle of Thread
 1.Newborn State:
– When a thread object is created a new thread is born
and said to be in Newborn state.

 2.Runnable State:
– If a thread is in this state it means that the thread is
ready for execution and waiting for the availability of
the processor.
– If all threads in queue are of same priority then they
are given time slots for execution in round robin
fashion

By D. Durai kumar, HOD / IT


4.2 Thread Life Cycle
Life Cycle of Thread
 3.Running State:
 It means that the processor has given its time to the
thread for execution.
 A thread keeps running until the following conditions
occurs
 (a) Thread give up its control on its own and it can
happen in the following situations
• i.A thread gets suspended using suspend() method which can
only be revived with resume() method
• ii.A thread is made to sleep for a specified period of time
using sleep(time) method, where time in milliseconds
• iii.A thread is made to wait for some event to occur using
wait () method. In this case a thread can be scheduled to run
again using notify () method.
 (b) A thread is pre-empted by a higher priority thread
By D. Durai kumar, HOD / IT
4.2 Thread Life Cycle
Life Cycle of Thread
 4. Blocked State:
– If a thread is prevented from entering into runnable
state and subsequently running state, then a thread is
said to be in Blocked state.
 5. Dead State:
– A runnable thread enters the Dead or terminated state
when it completes its task or otherwise

By D. Durai kumar, HOD / IT


4.3 The Main Thread
The Main Thread
 When we run any java program, the program begins to
execute its code starting from the main method.
 Therefore, the JVM creates a thread to start executing the
code present in main method. This thread is called as
main thread.
 Although the main thread is automatically created, you
can control it by obtaining a reference to it by calling
currentThread() method.
 Two important things to know about main thread are,
– It is the thread from which other threads will be
produced.
– main thread must be always the last thread to finish
execution.
By D. Durai kumar, HOD / IT
4.3 The Main Thread
The Main Thread
Example
class MainThread
{
public static void main(String[] args)
{
Thread t1=Thread.currentThread();
t1.setName("MainThread");
System.out.println("Name of thread is "+t1);
}
}

By D. Durai kumar, HOD / IT


4.3 The Main Thread
The Main Thread
Example
class MainThread
{
public static void main(String[] args)
{
Thread t1=Thread.currentThread();
t1.setName("MainThread");
System.out.println("Name of thread is "+t1);
}
}

Output: Name of thread is Thread[MainThread,5,main]


By D. Durai kumar, HOD / IT
4.4 The Creation of Thread
Creation Of Thread
 Thread Can Be Implemented In Two Ways
1) Implementing Runnable Interface
2) Extending Thread Class

1.Create Thread by Implementing Runnable


 The easiest way to create a thread is to create a class that
implements the Runnable interface.
 To implement Runnable, a class need only implement a
single method called run()

By D. Durai kumar, HOD / IT


4.4 The Creation of Thread
Creation Of Thread
1.Create Thread by Implementing Runnable

By D. Durai kumar, HOD / IT


4.4 The Creation of Thread
Creation Of Thread
1.Create Thread by Implementing Runnable

By D. Durai kumar, HOD / IT


4.4 The Creation of Thread
Creation Of Thread
 Thread Can Be Implemented In Two Ways
1) Implementing Runnable Interface
2) Extending Thread Class

2. Extending Thread Class


 The second way to create a thread is to create a new class
that extends Thread, and then to create an instance of that
class.
 The extending class must override the run( ) method,
which is the entry point for the new thread.
 It must also call start( ) to begin execution of the new
thread.

By D. Durai kumar, HOD / IT


4.4 The Creation of Thread
Creation Of Thread
2. Extending Thread Class

By D. Durai kumar, HOD / IT


4.5 Thread Priority
 Each thread have a priority.
 Priorities are represented by a number between 1 and 10.
 Thread scheduler schedules the threads according to their
priority (known as preemptive scheduling).
 But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses.
 3 constants defined in Thread class:
• public static int MIN_PRIORITY
• public static int NORM_PRIORITY
• public static int MAX_PRIORITY
 Default priority of a thread is 5 (NORM_PRIORITY).
 The value of MIN_PRIORITY is 1
 The value of MAX_PRIORITY is 10.
By D. Durai kumar, HOD / IT
4.5 Thread Priority
 Example

By D. Durai kumar, HOD / IT


4.5 Thread Priority
 Example

By D. Durai kumar, HOD / IT


4.5 Thread Priority
 Example

By D. Durai kumar, HOD / IT


4.5 Synchronizing Threads
Synchronizing Threads
 o Synchronization in java is the capability to control the
access of multiple threads to any shared resource.
 o Java Synchronization is better option where we want to
allow only one thread to access the shared resource

 General Syntax :
synchronized(object)
{
//statement to be synchronized
}

By D. Durai kumar, HOD / IT


4.5 Synchronizing Threads
 Why use Synchronization
The synchronization is mainly used to
 o To prevent thread interference.
 o To prevent consistency problem.

By D. Durai kumar, HOD / IT


4.5 Synchronizing Threads
 Types of Synchronization
There are two types of synchronization
 Process Synchronization
 Thread Synchronization
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)


By D. Durai kumar, HOD / IT
4.5 Synchronizing Threads
 Types of Synchronization

Thread Synchronization
 Synchronized method
 If you declare any method as synchronized, it is
known as synchronized method.
 Synchronized method is used to lock an object for any
shared resource.
 When a thread invokes a synchronized method, it
automatically acquires the lock for that object and
releases it when the thread completes its task.

By D. Durai kumar, HOD / IT


4.5 Synchronizing Threads
 Types of Synchronization
 Synchronized method

By D. Durai kumar, HOD / IT


4.5 Synchronizing Threads
 Types of Synchronization
Thread Synchronization
 Synchronized block.
 Synchronized block can be used to perform
synchronization on any specific resource of the method.
 Suppose you have 50 lines of code in your method, but
you want to synchronize only 5 lines, you can use
synchronized block.
 If you put all the codes of the method in the
synchronized block, it will work same as the
synchronized method.

By D. Durai kumar, HOD / IT


4.5 Synchronizing Threads
 Types of Synchronization
 Synchronized block.

By D. Durai kumar, HOD / IT


4.5 Synchronizing Threads
 Types of Synchronization
Thread Synchronization
 Static synchronization
 If you make any static method as synchronized, the lock
will be on the class not on object.
 Example of static synchronization
 In this example we are applying synchronized keyword
on the static method to perform static synchronization

By D. Durai kumar, HOD / IT


4.5 Synchronizing Threads
 Types of Synchronization
Thread Synchronization
 Static synchronization
 If you make any static method as synchronized, the lock
will be on the class not on object.
 Example of static synchronization
 In this example we are applying synchronized keyword
on the static method to perform static synchronization

By D. Durai kumar, HOD / IT


4.5 Synchronizing Threads
 Types of Synchronization
 Static synchronization

By D. Durai kumar, HOD / IT


4.6 Inter Thread Communication
 Inter-thread communication
 Inter-thread communication or Co-operation is all about
allowing synchronized threads to communicate with each
other.
 Inter-thread communication is a mechanism in which a
thread is paused running in its critical section and another
thread is allowed to enter (or lock) in the same critical
section to be executed.
 It is implemented by following methods of Object class:
 wait()
 notify()
 notifyAll()

By D. Durai kumar, HOD / IT


4.6 Inter Thread Communication
 Inter-thread communication
 wait()
Tells calling thread to give up monitor and go to
sleep until some other thread enters the same monitor and
call notify.
 notify()
wakes up a thread that called wait() on same object.
 notifyAll()
wakes up all the thread that called wait() on same
object.

By D. Durai kumar, HOD / IT


4.6 Inter Thread Communication
 Inter-thread communication

By D. Durai kumar, HOD / IT


4.6 Inter Thread Communication
 Inter-thread communication
Understanding the process of inter-thread
communication

By D. Durai kumar, HOD / IT


4.6 Inter Thread Communication
 Inter-thread communication
Understanding the process of inter-thread
communication
The point to point explanation of the above diagram is as follows:
 Threads enter to acquire lock.
 Lock is acquired by on thread.
 Now thread goes to waiting state if you call wait() method on
the object. Otherwise it releases the lock and exits.
 If you call notify() or notifyAll() method, thread moves to the
notified state (runnable state).
 Now thread is available to acquire lock.
 After completion of the task, thread releases the lock and exits
the monitor state of the object.

By D. Durai kumar, HOD / IT


4.6 Inter Thread Communication
 Inter-thread communication

By D. Durai kumar, HOD / IT


4.6 Inter Thread Communication
 Inter-thread communication

By D. Durai kumar, HOD / IT


4.6 Inter Thread Communication
 Inter-thread communication

By D. Durai kumar, HOD / IT


4.6 Inter Thread Communication
 Inter-thread communication

By D. Durai kumar, HOD / IT


4.7 Daemon Thread in Java
 Daemon Thread in Java
 Daemon thread in java is a service provider thread
that provides services to the user thread.
 Its life depend on the mercy of user threads
 i.e. when all the user threads dies, JVM terminates
this thread automatically.

By D. Durai kumar, HOD / IT


4.7 Daemon Thread in Java
 Daemon Thread in Java

By D. Durai kumar, HOD / IT


4.7 Daemon Thread in Java
 Daemon Thread in Java

By D. Durai kumar, HOD / IT


4.7 a. Thread pool
 Java Thread pool represents a group of worker threads
that are waiting for the job and reused many times.
 In the case of a thread pool, a group of fixed-size threads
is created. A thread from the thread pool is pulled out
and assigned a job by the service provider. After
completion of the job, the thread is contained in the
thread pool again.
Thread Pool Methods:
 newFixedThreadPool(int s): The method creates a
thread pool of the fixed size s.
 newCachedThreadPool(): The method creates a new
thread pool that creates the new threads when needed but
will still use the previously created thread whenever they
are available to use.

By D. Durai kumar, HOD / IT


4.8 Thread Group
 Thread Group
 Java provides a convenient way to group multiple threads
in a single object.
 In such way, we can suspend, resume or interrupt group
of threads by a single method call.

 Constructors of ThreadGroup class


 There are only two constructors of ThreadGroup class.
1.ThreadGroup(String name)-creates a thread group
with given name.
2.ThreadGroup(ThreadGroup parent, String name)-
creates a thread group with given parent group and name.

By D. Durai kumar, HOD / IT


4.8 Thread Group
 Important methods of ThreadGroup class
 There are many methods in ThreadGroup class. A list of
important methods are given below.
– 1)int activeCount()-returns no. of threads running in
current group.
– 2)int activeGroupCount()-returns a no. of active
group in this thread group.
– 3)void destroy()-destroys this thread group and all its
sub groups.
– 4)String getName()-returns the name of this group.
– 5)ThreadGroup getParent()-returns the parent of this
group.
– 6)void interrupt()-interrupts all threads of this group.
– 7)void list()-prints information of this group to
standard console.By D. Durai kumar, HOD / IT
4.8 Thread Group

By D. Durai kumar, HOD / IT

You might also like