SlideShare a Scribd company logo
1 of 72
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.
Exceptions
• An exception is an unexpected event, which may
occur during the execution of a program(at run time)
• It disrupt the normal flow of the program’s
instructions
• This leads to the abnormal termination of the program
- not always recommended
• these exceptions are needed to be handled
• exception handling in java is one of the powerful
mechanisms to handle the runtime errors so that
normal flow of the application can be maintained
An exception may occur due to the following reasons:
– Invalid data as input
– Network connection may be disturbed in the middle of
communications
– JVM may run out of memory
– File cannot be found/opened
• These exceptions are caused by user error, programmer
error, and physical resources
• Based on these, exceptions classified into three
categories:
• Checked exceptions −
– is an exception that occurs at the compile time, also called
compile time (static time) exceptions
– These exceptions cannot be ignored at the time of compilation.
So, the programmer should handle these exceptions.
• Unchecked exceptions −
– is an exception that occurs at run time, also called as
Runtime Exceptions
– include programming bugs, such as logic errors or
improper use of an API
– It ignored at the time of compilation
• Errors −
– Errors are not exceptions, but problems may arise beyond
the control of the user or the programmer
– Errors are typically ignored in your code because you can
rarely do anything about an error
– For example, if a stack overflow occurs, an error will arise
– They are also ignored at the time of compilation
Difference between Error and Exception
• 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.
• Exceptions:
– conditions within the code. A developer can handle such
conditions and take necessary corrective actions
– Few examples
• Divide By Zero exception
• Null Pointer Exception
• Arithmetic Exception
• Array Index out of Bounds Exception
Exception Hierarchy
• The java.lang.Exception class is the base class for all
exception classes
• All exception and errors types are sub classes of class
Throwable, which is base class of hierarchy
• One branch is headed by Exception
– This class is used for exceptional conditions that user programs
should catch
– NullPointerException is an example of such an exception
• Another branch, Error are used by the Java run-time
system(JVM)
– indicate errors having to do with the runtime environment
itself(JRE)
– StackOverflowError is an example of such an error
• Exception class has two main subclasses:
IOException class and RuntimeException Class.
• Key words used in Exception handling
• There are 5 keywords used in java exception handling
keywords description
1. try A try/catch block is placed around the code that might
generate an exception. Code within a try/catch block
is referred to as protected code.
2. catch A catch statement involves declaring the type of
exception we are trying to catch.
3. finally A finally block of code always executes, irrespective
of occurrence of an Exception.
4. throw It is used to execute important code such as closing
connection, stream etc. throw is used to invoke an
exception explicitly.
5. throws throws is used to postpone the handling of a checked
exception.
The try/catch block is used as follows:
try {
// block of code to monitor for errors
// the code you think can raise an exception
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType
}
// optional
finally {
// block of code to be executed after try block ends
}
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}
• Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
//ArrayindexoutofBounds Exception
public class ExcepTest
{
public static void main(String args[])
{ int a[] = new int[2];
try
{ System.out.println("Access element three :" +a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("Exception thrown :" + e);
}
finally
{
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is
executed");
} } }
Output
Exception thrown
:java.lang.ArrayIndexOutOfBoundsE
ception:3
First element value: 6
The finally statement is executed
Note : here array size is 2 but we
are trying to access 3rdelement.
Throwing and catching exceptions
Catching Exceptions
• A method catches an exception using a combination of the try and
catch keywords.
• The program code that may generate an exception should be placed
inside the try/catch block.
• Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
• The code prone exceptions placed in the try block
• When an exception occurs, that handled by catch block
• Every try block should be immediately followed either by a catch
block or finally block.
• A catch statement involves declaring the type of exception
that tried to catch
• If an exception occurs, then catch block (or blocks) which
follow the try block is checked.
• If the type of exception that occurred is listed in a catch
block, the exception is passed to the catch block similar to
an argument that is passed into a method parameter
• Multiple catch Clauses
• In some cases, more than one exception could be raised by a
single piece of code.
• To handle this, two or more catch clauses can be specified.
• Here, each catch block catches different type of exception.
• When an exception is thrown, each catch statement is
inspected in order, and 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 try/catch block.
Nested try block
• 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.
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
• Throw keyword
• The Java throw keyword is used to explicitly throw an exception.
• general form :
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 to obtain a Throwable object:
1. using a parameter in a catch clause
2. creating one with the new operator.
Example:
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
• Output:
Exception in thread main java.lang.ArithmeticException:not valid
The Finally Block
• The finally block follows a try block or a catch block.
• A finally block of code always executes, irrespective of the occurrence of
an Exception.
• A finally block appears at the end of the catch blocks
• Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
}
finally {
// The finally block always executes.
}
Built-in exceptions
• Built-in exceptions are the exceptions which are available in Java
libraries.
Exceptions Description
Arithmetic Exception It is thrown when an exceptional condition has occurred
in an arithmetic operation
Array Index Out Of Bound
Exception
It is thrown to indicate that 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.
ClassNotFoundException This Exception is raised when we try to access a class
whose definition is not found.
FileNotFoundException This Exception is raised when a file is not accessible
or does not open.
IOException It is thrown when an input-output operation failed or
interrupted.
InterruptedException It is thrown when a thread is waiting, sleeping, or doing
some processing, and it is interrupted.
Exceptions Description
NoSuchFieldException It is thrown when a class does not contain the field (or
variable) specified.
NoSuchMethodException It is thrown when accessing a method which is not
found.
NullPointerException This exception is raised when referring to the members
of a null object. Null represents nothing.
NumberFormatException This exception is raised when a method could not convert
a string into a numeric format.
RuntimeException This represents any exception which occurs during
runtime
StringIndexOutOfBounds
Exception
It is thrown by String class methods to indicate that an
index is either negative than the size of the string
User defined exception
• Java allows the user to create their own exception class which is
derived from built in class Exception.
• The Exception class inherits all the methods from the class
Throwable.
• The Throwable class is the superclass of all errors and exceptions in
the Java language.
• It contains a snapshot of the execution stack of its thread at the
time it was created.
• It can also contain a message string that gives more information
about the error.
– The Exception class is defined in java.lang package.
– User defined exception class must inherit Exception class.
– The user defined exception can be thrown using throw keyword.
• Syntax:
class User_defined_name extends Exception{
………..
}
• Program to create user defined exception that test for odd numbers.
import java.util.Scanner;
class OddNumberException extends Exception
{
OddNumberException() //default constructor
{
super(“Odd number exception”);
}
OddNumberException(String msg) //parameterized constructor
{
super(msg);
}}
public class UserdefinedExceptionDemo{
public static void main(String[] args)
{
int num;
Scanner Sc = new Scanner(System.in); // create Scanner object to
read input
System.out.println(“Enter a number : “);
num = Integer.parseInt(Sc.nextLine());
try
{
if(num%2 != 0) // test for odd number
throw(new OddNumberException()); // raise the exception if number
is odd
else
System.out.println(num + “ is an even number”);
}
catch(OddNumberException Ex)
{
System.out.print(“ntError : “ + Ex.getMessage());
}}
}
Sample Output1:
Enter a number : 11
Error : Odd number exception
Sample Output2:
10 is an even number
Multithreaded Programming
• Java provides built-in support for multithreaded
programming
• 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.
• Multithreading is a specialized form of multitasking.
• Two distinct types of multitasking:
– Process based
– Thread based
• Process - a program that is executing
• process-based multitasking is the feature that allows your
computer to run two or more programs concurrently
• Example: run the Java compiler at the same time that are
using a text editor
• Thread-based multitasking environment, the thread is the
smallest unit of dispatch able code
• Single program can perform two or more tasks
simultaneously
• a text editor can format text at the same time that it is
printing
• these two actions are being performed by two separate
threads
Comparison between multithreading
and multi-tasking
Parameter Multi Tasking Multi Threading
Basic Multitasking lets CPU to
execute
multiple tasks at the same
time.
Multithreading lets CPU to
execute
multiple threads of a process
simultaneously.
Execution the CPU switches between
multiple processes to
complete the execution.
the CPU switches between
multiple threads in the same
process.
Memory and
Resource
system has to allocate
separate memory and
resources to each program
that CPU is executing.
system has to allocate memory to a
process, multiple threads of that
process shares the same memory
and resources allocated to the
process.
Complexity Multitasking is heavy-weight
and harder to create.
Multithreading is light-weight and
easy to create.
Thread Lifecycle
• A thread in Java at any point of time exists in any one of
the following states.
• A thread lies only in one of the shown states at any
instant:
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
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
• 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
• At any time, a thread can be terminated, which
halts its execution immediately.
• Once terminated, a thread cannot be resumed.
Creating Threads
• Threading is a facility to allow multiple tasks to
run concurrently within a single process.
• Threads are independent, concurrent execution
through a program, and each thread has its own
stack.
• two ways to create a thread:
1) By extending Thread class
2) By implementing Runnable interface
Thread class:
• Thread class provide constructors and methods to
create and perform operations on a thread.
• Thread class extends Object class and implements
Runnable interface.
• Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)
• 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.
3. public void sleep(long miliseconds): Causes the
currently executing thread to sleep(temporarily
stop execution) for the specified number of
milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread
to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the
thread.
7. public int setPriority(int priority): changes the
priority of the thread.
8. public String getName(): returns the name of the
thread.
9. public void setName(String name): changes the name
of the thread.
10. public Thread currentThread(): returns the reference
of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the
thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing
thread object to temporarily pause and allow other
threads to execute
15. public void suspend(): is used to suspend the thread
16. public void resume(): is used to resume the suspended
thread
17.public void stop(): is used to stop the thread
18. public boolean isDaemon(): tests if the thread
is a daemon thread.
19. public void setDaemon(boolean b): marks
the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the
thread has been interrupted.
22. public static boolean interrupted(): tests if the
current thread has been interrupted
• Naming Thread
• The Thread class provides methods to change and get
the name of a thread.
• By default, each thread has a name i.e. thread-0,
thread-1 and so on.
• But we can change the name of the thread by using
setName() method.
• The syntax of setName() and getName() methods:
public String getName(): is used to return the name of
a thread.
public void setName(String name): is used to change
the name of a thread.
• Extending Thread
• 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.
• // Create a second thread by extending Thread
class NewThread extends Thread
{
NewThread()
{ // Create a new, second thread
super(“Demo Thread”);
System.out.println(“Child thread: “ + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(“Child Thread: “ + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println(“Child interrupted.”);
}
System.out.println(“Child thread is exiting”);
}}
public class ExtendThread
{
public static void main(String args[])
{
new NewThread(); // create a new thread
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(“Main Thread: “ + i);
Thread.sleep(1000);
}}
catch (InterruptedException e)
{
System.out.println(“Main thread interrupted.”);
}
System.out.println(“Main thread is exiting.”);
}
}
Sample Output:
(output may vary based on processor speed and task load)
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Child thread is exiting.
Main Thread: 2
Main Thread: 1
Main thread is exiting.
• Implementing Runnable
• The easiest way to create a thread is to create a class that
implements the Runnable interface
• we will instantiate an object of type Thread from within
that class.
• After the new thread is created, it will not start running
until we call its start( ) method, which is declared within
Thread.
• In essence, start( ) executes a call to run( ).
• The start( ) method is shown as:
void start( )
• To implement Runnable, a class need only implement a
single method called run()
class NewThread implements Runnable
{
Thread t;
NewThread()
{
// Create a new, second thread
t = new Thread(this, “Demo Thread”);
System.out.println(“Child thread: “ + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(“Child Thread: “ + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println(“Child interrupted.”);
}
System.out.println(“Child thread is exiting.”);
}
}
public class ThreadDemo
{
public static void main(String args[])
{
new NewThread(); // create a new thread
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(“Main Thread: “ + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(“Main thread
interrupted.”);
}
System.out.println(“Main thread is exiting.”);
}
}
Sample Output:
(output may vary based on processor
speed and task load)
Child thread: Thread[Demo
Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Child thread is exiting.
Main Thread: 2
Main Thread: 1
Main thread is exiting.
Synchronizing Threads
• Synchronization in java is the capability to control the
access of multiple threads to any shared resource.
• Java Synchronization is better option where we want
to allow only one thread to access the shared resource
• Why use Synchronization
• To prevent thread interference
• To prevent consistency problem
• Types of Synchronization
• Process Synchronization
• Thread Synchronization
• Thread Synchronization (two types )
1. Mutual Exclusive
• Synchronized method.
• Synchronized block.
• static synchronization.
2.Cooperation (Inter-thread communication in java)
Synchronized method
• declare any method as synchronized, it is known as
synchronized method.
• 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.
class Table
{
synchronized void printTable(int n)
{ //synchronized method
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{System.out.println(e);}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends
Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[])
{
Table obj = new Table();
//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
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, use synchronized
block
• If you put all the codes of the method in the
synchronized block, it will work same as the
synchronized method
• Syntax :
synchronized (object reference expression) {
//code block
}
class Table{
void printTable(int n)
{
synchronized(this)
{ //synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
Static synchronization
• make any static method as synchronized, the lock will
be on the class not on object
• applying synchronized keyword on the static method to
perform static synchronization.
class Table{
synchronized static void printTable(int n)
{
for(int i=1;i<=10;i++)
{ System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
} } }
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
} }
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
} }
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}
public class TestSynchronization4
{
public static void main(String t[])
{
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
t1.start();
t2.start();
t3.start();
}
}
Output:
1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400 500 600 700 800 900
Inter-thread communication
• Inter-thread communication or Co-operation is
allowing synchronized threads to communicate with
each other.
• 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.
• implemented by following methods of Object class:
• wait()
• notify()
• notifyAll()
• wait()
• tells calling thread to give up monitor and go
to sleep/ wait 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.
Difference between wait and sleep?
class Customer{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for
deposit...");
try{wait();}
catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
Daemon thread
• Daemon thread is a low priority thread that runs in
background to perform tasks such as garbage
collection
• Is a service provider thread that provides services to
the user thread
• Its life depend on the mercy of user threads
• when all the user threads dies, JVM terminates this
thread automatically
Methods for Java Daemon thread by
Thread class
Method Description
public void setDaemon(boolean status) used to mark the current thread as daemon
thread or user thread.
public boolean isDaemon() used to check that current is daemon.
public class DaemonThread extends Thread
{
public DaemonThread(String name){
super(name);
}
public void run()
{
// Checking whether the thread is Daemon or not
if(Thread.currentThread().isDaemon())
{
System.out.println(getName() + " is Daemon thread");
else
{
System.out.println(getName() + " is User thread");
}
}
public static void main(String[] args)
{
DaemonThread t1 = new DaemonThread("t1");
DaemonThread t2 = new DaemonThread("t2");
DaemonThread t3 = new DaemonThread("t3");
// Setting user thread t1 to Daemon
t1.setDaemon(true);
// starting first 2 threads
t1.start();
t2.start();
// Setting user thread t3 to Daemon
t3.setDaemon(true);
t3.start();
}
}
• Output:
t1 is Daemon thread
t2 is User thread
t3 is Daemon thread
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 : two constructors
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.
• Important methods of ThreadGroup class
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.
public class ThreadGroup_example implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadGroup_example runnable = new
ThreadGroup_example();
ThreadGroup tg1 = new ThreadGroup(“Parent ThreadGroup”);
Thread t1 = new Thread(tg1, runnable,”one”);
t1.start();
Thread t2 = new Thread(tg1, runnable,”two”);
t2.start();
Thread t3 = new Thread(tg1, runnable,”three”);
t3.start();
System.out.println(“Thread Group Name: “+tg1.getName());
tg1.list();
}
}
Sample Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread [one,5,Parent ThreadGroup]
Thread [two,5,Parent ThreadGroup]
Thread [three,5,Parent ThreadGroup
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 1000; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println(“Exception encounterted”);
}
}
}
}
public class ThreadGroup_example
{
public static void main(String arg[])
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup(“parent thread group”);
NewThread t1 = new NewThread(“one”, gfg);
System.out.println(“Starting one”);
NewThread t2 = new NewThread(“two”, gfg);
System.out.println(“Starting two”);
// checking the number of active thread
System.out.println(“number of active thread: “
+ gfg.activeCount());
}
}
Output:
Starting one
Starting two
number of active thread: 2
Exceptions and Multithreading in Java

More Related Content

Similar to Exceptions and Multithreading in Java

Similar to Exceptions and Multithreading in Java (20)

Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java class 7
Java class 7Java class 7
Java class 7
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
 
Exception
ExceptionException
Exception
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 

Recently uploaded

Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 

Recently uploaded (20)

Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 

Exceptions and Multithreading in Java

  • 1. 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.
  • 2. Exceptions • An exception is an unexpected event, which may occur during the execution of a program(at run time) • It disrupt the normal flow of the program’s instructions • This leads to the abnormal termination of the program - not always recommended • these exceptions are needed to be handled • exception handling in java is one of the powerful mechanisms to handle the runtime errors so that normal flow of the application can be maintained
  • 3. An exception may occur due to the following reasons: – Invalid data as input – Network connection may be disturbed in the middle of communications – JVM may run out of memory – File cannot be found/opened • These exceptions are caused by user error, programmer error, and physical resources • Based on these, exceptions classified into three categories: • Checked exceptions − – is an exception that occurs at the compile time, also called compile time (static time) exceptions – These exceptions cannot be ignored at the time of compilation. So, the programmer should handle these exceptions.
  • 4. • Unchecked exceptions − – is an exception that occurs at run time, also called as Runtime Exceptions – include programming bugs, such as logic errors or improper use of an API – It ignored at the time of compilation • Errors − – Errors are not exceptions, but problems may arise beyond the control of the user or the programmer – Errors are typically ignored in your code because you can rarely do anything about an error – For example, if a stack overflow occurs, an error will arise – They are also ignored at the time of compilation
  • 5. Difference between Error and Exception • 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. • Exceptions: – conditions within the code. A developer can handle such conditions and take necessary corrective actions – Few examples • Divide By Zero exception • Null Pointer Exception • Arithmetic Exception • Array Index out of Bounds Exception
  • 6. Exception Hierarchy • The java.lang.Exception class is the base class for all exception classes • All exception and errors types are sub classes of class Throwable, which is base class of hierarchy • One branch is headed by Exception – This class is used for exceptional conditions that user programs should catch – NullPointerException is an example of such an exception • Another branch, Error are used by the Java run-time system(JVM) – indicate errors having to do with the runtime environment itself(JRE) – StackOverflowError is an example of such an error
  • 7. • Exception class has two main subclasses: IOException class and RuntimeException Class.
  • 8. • Key words used in Exception handling • There are 5 keywords used in java exception handling keywords description 1. try A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code. 2. catch A catch statement involves declaring the type of exception we are trying to catch. 3. finally A finally block of code always executes, irrespective of occurrence of an Exception. 4. throw It is used to execute important code such as closing connection, stream etc. throw is used to invoke an exception explicitly. 5. throws throws is used to postpone the handling of a checked exception.
  • 9. The try/catch block is used as follows: try { // block of code to monitor for errors // the code you think can raise an exception } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType } // optional finally { // block of code to be executed after try block ends }
  • 10. public class JavaExceptionExample{ public static void main(String args[]){ try{ //code that may raise exception int data=100/0; } catch(ArithmeticException e) {System.out.println(e); } //rest code of the program System.out.println("rest of the code..."); } } • Output: Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code...
  • 11. //ArrayindexoutofBounds Exception public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" +a[3]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } finally { a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } } Output Exception thrown :java.lang.ArrayIndexOutOfBoundsE ception:3 First element value: 6 The finally statement is executed Note : here array size is 2 but we are trying to access 3rdelement.
  • 12. Throwing and catching exceptions Catching Exceptions • A method catches an exception using a combination of the try and catch keywords. • The program code that may generate an exception should be placed inside the try/catch block. • Syntax try { // Protected code } catch (ExceptionName e1) { // Catch block } • The code prone exceptions placed in the try block • When an exception occurs, that handled by catch block • Every try block should be immediately followed either by a catch block or finally block.
  • 13. • A catch statement involves declaring the type of exception that tried to catch • If an exception occurs, then catch block (or blocks) which follow the try block is checked. • If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block similar to an argument that is passed into a method parameter • Multiple catch Clauses • In some cases, more than one exception could be raised by a single piece of code. • To handle this, two or more catch clauses can be specified. • Here, each catch block catches different type of exception. • When an exception is thrown, each catch statement is inspected in order, and 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 try/catch block.
  • 14. Nested try block • 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. try { statement 1; statement 2; try { statement 1; statement 2; }
  • 15. catch(Exception e) { } } catch(Exception e) { } .... • Throw keyword • The Java throw keyword is used to explicitly throw an exception. • general form : 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
  • 16. • There are two ways to obtain a Throwable object: 1. using a parameter in a catch clause 2. creating one with the new operator. Example: public class TestThrow1{ static void validate(int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ validate(13); System.out.println("rest of the code..."); } }
  • 17. • Output: Exception in thread main java.lang.ArithmeticException:not valid The Finally Block • The finally block follows a try block or a catch block. • A finally block of code always executes, irrespective of the occurrence of an Exception. • A finally block appears at the end of the catch blocks • Syntax try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } finally { // The finally block always executes. }
  • 18. Built-in exceptions • Built-in exceptions are the exceptions which are available in Java libraries. Exceptions Description Arithmetic Exception It is thrown when an exceptional condition has occurred in an arithmetic operation Array Index Out Of Bound Exception It is thrown to indicate that 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. ClassNotFoundException This Exception is raised when we try to access a class whose definition is not found. FileNotFoundException This Exception is raised when a file is not accessible or does not open. IOException It is thrown when an input-output operation failed or interrupted. InterruptedException It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
  • 19. Exceptions Description NoSuchFieldException It is thrown when a class does not contain the field (or variable) specified. NoSuchMethodException It is thrown when accessing a method which is not found. NullPointerException This exception is raised when referring to the members of a null object. Null represents nothing. NumberFormatException This exception is raised when a method could not convert a string into a numeric format. RuntimeException This represents any exception which occurs during runtime StringIndexOutOfBounds Exception It is thrown by String class methods to indicate that an index is either negative than the size of the string
  • 20. User defined exception • Java allows the user to create their own exception class which is derived from built in class Exception. • The Exception class inherits all the methods from the class Throwable. • The Throwable class is the superclass of all errors and exceptions in the Java language. • It contains a snapshot of the execution stack of its thread at the time it was created. • It can also contain a message string that gives more information about the error. – The Exception class is defined in java.lang package. – User defined exception class must inherit Exception class. – The user defined exception can be thrown using throw keyword. • Syntax: class User_defined_name extends Exception{ ……….. }
  • 21. • Program to create user defined exception that test for odd numbers. import java.util.Scanner; class OddNumberException extends Exception { OddNumberException() //default constructor { super(“Odd number exception”); } OddNumberException(String msg) //parameterized constructor { super(msg); }} public class UserdefinedExceptionDemo{ public static void main(String[] args) { int num; Scanner Sc = new Scanner(System.in); // create Scanner object to read input
  • 22. System.out.println(“Enter a number : “); num = Integer.parseInt(Sc.nextLine()); try { if(num%2 != 0) // test for odd number throw(new OddNumberException()); // raise the exception if number is odd else System.out.println(num + “ is an even number”); } catch(OddNumberException Ex) { System.out.print(“ntError : “ + Ex.getMessage()); }} } Sample Output1: Enter a number : 11 Error : Odd number exception Sample Output2: 10 is an even number
  • 23. Multithreaded Programming • Java provides built-in support for multithreaded programming • 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. • Multithreading is a specialized form of multitasking. • Two distinct types of multitasking: – Process based – Thread based
  • 24. • Process - a program that is executing • process-based multitasking is the feature that allows your computer to run two or more programs concurrently • Example: run the Java compiler at the same time that are using a text editor • Thread-based multitasking environment, the thread is the smallest unit of dispatch able code • Single program can perform two or more tasks simultaneously • a text editor can format text at the same time that it is printing • these two actions are being performed by two separate threads
  • 25. Comparison between multithreading and multi-tasking Parameter Multi Tasking Multi Threading Basic Multitasking lets CPU to execute multiple tasks at the same time. Multithreading lets CPU to execute multiple threads of a process simultaneously. Execution the CPU switches between multiple processes to complete the execution. the CPU switches between multiple threads in the same process. Memory and Resource system has to allocate separate memory and resources to each program that CPU is executing. system has to allocate memory to a process, multiple threads of that process shares the same memory and resources allocated to the process. Complexity Multitasking is heavy-weight and harder to create. Multithreading is light-weight and easy to create.
  • 26. Thread Lifecycle • A thread in Java at any point of time exists in any one of the following states. • A thread lies only in one of the shown states at any instant: 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
  • 27.
  • 28. 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
  • 29. • 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 • At any time, a thread can be terminated, which halts its execution immediately. • Once terminated, a thread cannot be resumed.
  • 30. Creating Threads • Threading is a facility to allow multiple tasks to run concurrently within a single process. • Threads are independent, concurrent execution through a program, and each thread has its own stack. • two ways to create a thread: 1) By extending Thread class 2) By implementing Runnable interface
  • 31. Thread class: • Thread class provide constructors and methods to create and perform operations on a thread. • Thread class extends Object class and implements Runnable interface. • Commonly used Constructors of Thread class: • Thread() • Thread(String name) • Thread(Runnable r) • Thread(Runnable r, String name)
  • 32. • 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. 3. public void sleep(long miliseconds): Causes the currently executing thread to sleep(temporarily stop execution) for the specified number of milliseconds. 4. public void join(): waits for a thread to die.
  • 33. 5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds. 6. public int getPriority(): returns the priority of the thread. 7. public int setPriority(int priority): changes the priority of the thread. 8. public String getName(): returns the name of the thread. 9. public void setName(String name): changes the name of the thread. 10. public Thread currentThread(): returns the reference of currently executing thread.
  • 34. 11. public int getId(): returns the id of the thread. 12. public Thread.State getState(): returns the state of the thread. 13. public boolean isAlive(): tests if the thread is alive. 14. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute 15. public void suspend(): is used to suspend the thread 16. public void resume(): is used to resume the suspended thread 17.public void stop(): is used to stop the thread
  • 35. 18. public boolean isDaemon(): tests if the thread is a daemon thread. 19. public void setDaemon(boolean b): marks the thread as daemon or user thread. 20. public void interrupt(): interrupts the thread. 21. public boolean isInterrupted(): tests if the thread has been interrupted. 22. public static boolean interrupted(): tests if the current thread has been interrupted
  • 36. • Naming Thread • The Thread class provides methods to change and get the name of a thread. • By default, each thread has a name i.e. thread-0, thread-1 and so on. • But we can change the name of the thread by using setName() method. • The syntax of setName() and getName() methods: public String getName(): is used to return the name of a thread. public void setName(String name): is used to change the name of a thread.
  • 37. • Extending Thread • 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. • // Create a second thread by extending Thread class NewThread extends Thread { NewThread() { // Create a new, second thread super(“Demo Thread”); System.out.println(“Child thread: “ + this); start(); // Start the thread }
  • 38. // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println(“Child Thread: “ + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println(“Child interrupted.”); }
  • 39. System.out.println(“Child thread is exiting”); }} public class ExtendThread { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println(“Main Thread: “ + i); Thread.sleep(1000); }} catch (InterruptedException e) { System.out.println(“Main thread interrupted.”); }
  • 40. System.out.println(“Main thread is exiting.”); } } Sample Output: (output may vary based on processor speed and task load) Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Child thread is exiting. Main Thread: 2 Main Thread: 1 Main thread is exiting.
  • 41. • Implementing Runnable • The easiest way to create a thread is to create a class that implements the Runnable interface • we will instantiate an object of type Thread from within that class. • After the new thread is created, it will not start running until we call its start( ) method, which is declared within Thread. • In essence, start( ) executes a call to run( ). • The start( ) method is shown as: void start( ) • To implement Runnable, a class need only implement a single method called run()
  • 42. class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, “Demo Thread”); System.out.println(“Child thread: “ + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { try {
  • 43. for(int i = 5; i > 0; i--) { System.out.println(“Child Thread: “ + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println(“Child interrupted.”); } System.out.println(“Child thread is exiting.”); } } public class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread
  • 44. try { for(int i = 5; i > 0; i--) { System.out.println(“Main Thread: “ + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(“Main thread interrupted.”); } System.out.println(“Main thread is exiting.”); } } Sample Output: (output may vary based on processor speed and task load) Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Child thread is exiting. Main Thread: 2 Main Thread: 1 Main thread is exiting.
  • 45. Synchronizing Threads • Synchronization in java is the capability to control the access of multiple threads to any shared resource. • Java Synchronization is better option where we want to allow only one thread to access the shared resource • Why use Synchronization • To prevent thread interference • To prevent consistency problem • Types of Synchronization • Process Synchronization • Thread Synchronization
  • 46. • Thread Synchronization (two types ) 1. Mutual Exclusive • Synchronized method. • Synchronized block. • static synchronization. 2.Cooperation (Inter-thread communication in java) Synchronized method • declare any method as synchronized, it is known as synchronized method. • 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.
  • 47. class Table { synchronized void printTable(int n) { //synchronized method for(int i=1;i<=5;i++) { System.out.println(n*i); try { Thread.sleep(400); } catch(Exception e) {System.out.println(e);} } } }
  • 48. class MyThread1 extends Thread { Table t; MyThread1(Table t) { this.t=t; } public void run() { t.printTable(5); } } class MyThread2 extends Thread { Table t; MyThread2(Table t) { this.t=t; } public void run() { t.printTable(100); } }
  • 49. public class TestSynchronization2{ public static void main(String args[]) { Table obj = new Table(); //only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } } Output: 5 10 15 20 25 100 200 300 400 500
  • 50. 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, use synchronized block • If you put all the codes of the method in the synchronized block, it will work same as the synchronized method • Syntax : synchronized (object reference expression) { //code block }
  • 51. class Table{ void printTable(int n) { synchronized(this) { //synchronized block for(int i=1;i<=5;i++) { System.out.println(n*i); try{ Thread.sleep(400); } catch(Exception e){System.out.println(e);} } } }//end of the method }
  • 52. Static synchronization • make any static method as synchronized, the lock will be on the class not on object • applying synchronized keyword on the static method to perform static synchronization. class Table{ synchronized static void printTable(int n) { for(int i=1;i<=10;i++) { System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){} } } }
  • 53. class MyThread1 extends Thread{ public void run(){ Table.printTable(1); } } class MyThread2 extends Thread{ public void run(){ Table.printTable(10); } } class MyThread3 extends Thread{ public void run(){ Table.printTable(100); } }
  • 54. public class TestSynchronization4 { public static void main(String t[]) { MyThread1 t1=new MyThread1(); MyThread2 t2=new MyThread2(); MyThread3 t3=new MyThread3(); t1.start(); t2.start(); t3.start(); } } Output: 1 2 3 4 5 6 7 8 9 10 10 20 30 40 50 60 70 80 90 100 100 200 300 400 500 600 700 800 900
  • 55. Inter-thread communication • Inter-thread communication or Co-operation is allowing synchronized threads to communicate with each other. • 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. • implemented by following methods of Object class: • wait() • notify() • notifyAll()
  • 56. • wait() • tells calling thread to give up monitor and go to sleep/ wait 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.
  • 58. class Customer{ int amount=10000; synchronized void withdraw(int amount) { System.out.println("going to withdraw..."); if(this.amount<amount){ System.out.println("Less balance; waiting for deposit..."); try{wait();} catch(Exception e){} } this.amount-=amount; System.out.println("withdraw completed..."); }
  • 59. synchronized void deposit(int amount) { System.out.println("going to deposit..."); this.amount+=amount; System.out.println("deposit completed... "); notify(); } } class Test{ public static void main(String args[]) { final Customer c=new Customer();
  • 60. new Thread() { public void run(){c.withdraw(15000);} }.start(); new Thread(){ public void run(){c.deposit(10000);} }.start(); }} Output: going to withdraw... Less balance; waiting for deposit... going to deposit... deposit completed... withdraw completed
  • 61. Daemon thread • Daemon thread is a low priority thread that runs in background to perform tasks such as garbage collection • Is a service provider thread that provides services to the user thread • Its life depend on the mercy of user threads • when all the user threads dies, JVM terminates this thread automatically
  • 62. Methods for Java Daemon thread by Thread class Method Description public void setDaemon(boolean status) used to mark the current thread as daemon thread or user thread. public boolean isDaemon() used to check that current is daemon. public class DaemonThread extends Thread { public DaemonThread(String name){ super(name); } public void run() { // Checking whether the thread is Daemon or not if(Thread.currentThread().isDaemon()) { System.out.println(getName() + " is Daemon thread");
  • 63. else { System.out.println(getName() + " is User thread"); } } public static void main(String[] args) { DaemonThread t1 = new DaemonThread("t1"); DaemonThread t2 = new DaemonThread("t2"); DaemonThread t3 = new DaemonThread("t3"); // Setting user thread t1 to Daemon t1.setDaemon(true);
  • 64. // starting first 2 threads t1.start(); t2.start(); // Setting user thread t3 to Daemon t3.setDaemon(true); t3.start(); } } • Output: t1 is Daemon thread t2 is User thread t3 is Daemon thread
  • 65. 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 : two constructors 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.
  • 66. • Important methods of ThreadGroup class 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.
  • 67. public class ThreadGroup_example implements Runnable{ public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { ThreadGroup_example runnable = new ThreadGroup_example(); ThreadGroup tg1 = new ThreadGroup(“Parent ThreadGroup”); Thread t1 = new Thread(tg1, runnable,”one”); t1.start(); Thread t2 = new Thread(tg1, runnable,”two”); t2.start(); Thread t3 = new Thread(tg1, runnable,”three”); t3.start();
  • 68. System.out.println(“Thread Group Name: “+tg1.getName()); tg1.list(); } } Sample Output: one two three Thread Group Name: Parent ThreadGroup java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10] Thread [one,5,Parent ThreadGroup] Thread [two,5,Parent ThreadGroup] Thread [three,5,Parent ThreadGroup
  • 69. import java.lang.*; class NewThread extends Thread { NewThread(String threadname, ThreadGroup tgob) { super(tgob, threadname); start(); } public void run() { for (int i = 0; i < 1000; i++) { try { Thread.sleep(10); }
  • 70. catch (InterruptedException ex) { System.out.println(“Exception encounterted”); } } } } public class ThreadGroup_example { public static void main(String arg[]) { // creating the thread group ThreadGroup gfg = new ThreadGroup(“parent thread group”);
  • 71. NewThread t1 = new NewThread(“one”, gfg); System.out.println(“Starting one”); NewThread t2 = new NewThread(“two”, gfg); System.out.println(“Starting two”); // checking the number of active thread System.out.println(“number of active thread: “ + gfg.activeCount()); } } Output: Starting one Starting two number of active thread: 2