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

4.exception Handling and Multithreading

Uploaded by

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

4.exception Handling and Multithreading

Uploaded by

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

4.

Exception Handling And Multithreading

--Errors in situation which prevents the normal execution of our programs.


-- Error is an illegal operation performed by the user which results in the
abnormal working of the program.
-- Programming errors often remain undetected until the program is
compiled or executed.
-- Some of the errors inhibit the program from getting compiled or
executed. Thus errors should be removed before compiling and executing.
--it is obvious responsibility of a programmer to deal with all kinds of
errors.
--There are generally Three Types of Errors:
1.Syntax Error
2.Runtime Error
3.Logical Error.
Types of Error

1.Syntax Errors
--Syntax error refer to the grammatical errors
while writing the code of program.
--Examples are:
1.Misspelled variable and Function names.
2.Missing semicolons;
3.Improperly matching parentheses,square
brackets,and curly braces.
4.Incorrect format in selection and loop
statement.
2.Runtime Error
--Runtime error occur when a program with no syntax error asks the computer
to do something that the computer is unable to reliably.
--These errors occur in the run mode of a program.
--Examples:
1.Trying to divide by a variable that contains value zero.
2.Trying to open a file that does’nt exist.
3.Logical Error
--Logical errors occurs when there is something wrong in the logic of
program.
--Examples:
1.Multitasking when you should be dividing.
2.Adding when you should be subtracting.
3.Opening and using data from the wrong file.
4.Displaying the wrong message
Advantage of Exception Handling
• The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application;
that is why we need to handle exceptions.
• statement 1;
• statement 2;
• statement 3;
• statement 4;
• statement 5;//exception occurs
• statement 6;
• statement 7;
• statement 8;
• statement 9;
• statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at
statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will
not be executed. However, when we perform exception handling, the rest of the
statements will be executed. That is why we use exception handling in Java.
Exception Classes-Subclasses
--All exception classes are considered as the subtype of the java.lang.Exception classes.
--The class is extended from the Throwable class.
--With Exception,one or more class is present named Error which is extended from the Throwable class.
--Errors are unusual situations which occur in case of several failures,which are not handled by the java
programs.
--The Exception class has two main subclasses
:IOException class and RuntimeExceptionclass.
--Hierarchy of exception classes:

Object

Throwable

Stock over flow


Error Exception
Stock over flow Error Unchecked Except checked Exception
IOException
Runtime
. …etc Exception
Arithmetic Exception File Not Found
Except

Number Not found Except Class Not found


Except
Null pointer Exception .
. Array Index Out of Bound ………etc…….
……..etc
--An Exception is an event,which occur during the execution of a program that
interrupts the normal flow of the program.
--All the exception are usually handled by the java compiler.
--when an exception occurs,compiler provides an error message and terminate the
program.
-- Now consider program performing five tasks.if any exception occurs;say in second
task then the program will be the terrminated at the point and the remaining three
task will not be executed.
--Also the errors message displayed by java is not so much easy to understand for end
user.
--Now here user expects two things:
1.If exception is in second task,that they except second task remaining tasks should be
executed.
2.The error message should be easy to understand.
--To solve these problem,programmer has to explicitly handle the exception.
--There are many different reasons for the occurrence of the exception.some of them
are as follows:
 Invalid user input
 A file that needs to be opened can not be found.
 Server is down or network is failed.
 Printer or Scanner not working.
--These exception generate because of user error,programmer error,or by physical
resources such as printer or scanner that have failed in some manner.
Types of Exception
--There are basically two types of Exception:
1.Checked Exception
2.Unchecked Exception.
1.Checked Exception
--A checked exception occurs at the time of program compilation.
--It is also known as compile time exception.
--If some code within a method throws the checked exception,then the method must
either handle the exception or it must specify the exception using throws keyword.
--At runtime these exception may occur or not but it is responsibility of programmer to
compulsory handle the exception in the program by writing exception handling
code.
--Compiler does not execute the program if such code is not written.
• Example:IOException,SQLException,ClassNotFOundException,Interrupte
dException etc.
--All these are built in exception in java.
• 2.Unchecked Exception
--Unchecked Exception are the exceptions that are not checked at compile
time.That means it is not compulsory for the method to handle these
exception.
--Compiler does not check whether the method in which exception may occur
contains the exception handling code or not.
--Exception under Error and Runtime Exception classes are unchecked
exceptions.
--Example,Array Index Out Of Bounds Exception,Null Pointer
Exception,Arithmetic Exception,Number Format Exception etc.
Difference Between Checked And Unchecked Exceptio
Parameter
n
Checked Exception Unchecked Exception
Basic Checked exception are Unchecked exception
checked by compiler. does not checked by
compiler.

Class of Exception “Runtime exception and “RuntimeException” class


child class Exception will and its child classes,are
be handled in Checked Unchecked Exception.
Exception.

If not Checked Program does not Program executes.


execute.
Examples Example:IOException,SQ Example,Array Index Out
LException,ClassNotFOu Of Bounds
ndException,InterruptedE Exception,Null Pointer
xception etc. Exception,Arithmetic
Exception,Number
Format Exception
Try and Catch Block
--Java provides following keyword to handle the exception
1.Try 2.Catch 3.Finally 4.Throw 5. Throws.
1.Try Block
--now it is responsibility of a programmer to guess the code in which the
exception may occur.
--Try is a block in which we have to write the code in which the exception
may occur.
--Java try block is used to enclose the code that might throw an exception.
It must be used within the method.
-- If an exception occurs at the particular statement in the try block, the
rest of the block code will not execute. So, it is recommended not to keep
the code in try block that will not throw an exception.
--Java try block must be followed by either catch or finally block or both.
--when an exception occurs in try block ,it throws the exception which is
represented by an object.
Syntax:
try
{
Statements;
}
2.Catch Block
--This block is also known as Exception Handler.When an exception is thrown by try
block,then the suitable matching catch block catches the exception and handles it.
--In this block we have to create object for the particular exception as argument.
--Here we can give the easy to understand error message to be displayed when an
exception occurs.
--A single try block may have multiple catch block associated with it.
--Different exceptions can be caught in different catch blocks.
--when there is an exception in try block the corressponding catch block that handles
that particular exception executes.
--For example if there is arithmetic exception then the catch block containing object
for arithmetic exception gets executed.
--Program without handling exception.
--Example
class Exception
{
public static void main(String []args)
{
Int a=0,b=0res;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
res=a/b;
System.out.println(“Division is:”+res);

res=a+b;
System.out.println(“Adddition is:”+res);
}
}
--In this program Addition and division are two tasks,If user input is correct ,then it will produce proper output:
--Suppose user enter 10 and 5 then the output will be 15 and 2.but if user input second number as 0,it will
show error 10 and 0.Then error occur because division by zero is not allowed.
--But the important point is that there is no concern of second number as zero with next task of addition,but still
it does not execute because the program is terminated from the point where the error occurs.
--Now to handle this we have to use try and catch block.
Example:
--Accept two numbers as command line arguments and print the result of division and addition.Throw an
exception if user enters second number as zero.
class Exception
{
public static void main(String [] args)
{
int a=0,b=0,res;
try
{
a=a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
res=a/b;

System.out.println("Division is:"+res);
}
catch(ArithmeticException e)
{
System.out.println("Can not divide by zero:");
}
res=a+b;
System.out.println("Addition is:"+res);
}
}
--Here we can observe that when user enters second number as 0,then the programmer written error message is
displayed and most important factor is that the program is continued and the second task is executed.
--The divide by zero is associated with the ArithmeticException class of java,hence we have to create object for it in
catch block.
Nested try Statement
--Writing a try catch inside another try block is called as nested try block.
--when an exception occurs in inner try then matching inner catch is searched.
--if not found then the exception is transferred to outer catch.
--if the outer catch is also not able to handle it,then it will be handled by java runtime system.
Syntax:
try
{
try
{
----------
----------
}
catch()
{
----------
}
catch(---------)
{
------------
}
class NestedTry
{
public static void main(String[]

args)
{
int a,b,div;
try
{
try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
div=a/b;
System.out.println("Division

is:"+div);
}
catch(ArithmeticException e)
{
System.out.println("Cannot divide

by zero");
}
catch

(ArrayIndexOutOfBoundsException e)
{
System.out.println("Insufficient arguments:");
}
}
}
OUTPUT
1.5 0 =>can not divide by zero
2.5 =>Insufficient arguments
--In this example when second argument is passed as 0,then the arithmetic exception
occurs and caught by inner and handled.
--But when second argument is not passed,then ArrayIndexOutOfBoundsException
occur which can not caught by inner catch.Hence it is transferred to outer catch
which caught and handle it.
Multiple catch Blocks
--To handle multiple exception we have to create multiple catch blocks.
class MultiCatch
{
public static void main(String[]args)
{
int a=0,b=0,res;
try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
res=a/b;
System.out.println("Divide by zero:"+res);
}
catch(ArithmeticException e)
{
System.out.println("Cannot Divide by zero:");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Insufficient arguments:");
}
catch(NumberFormatException e)
{
System.out.println("Invalid arguments:");
}
res=a+b;
System.out.println("Addition is:"+res);
}
}
Finally

• It may be possible that programmer cannot guess


all the exception and does not write code to handle
all the types of expected exceptions.
• In such case if any exception occurs which is not
handled then the program will be terminated.
• Java provides a simple solution on it;Finally block.
• The code written in finally block gets executed even
if the error occurs which is not handled by
program.
• Means finally block gets executed in all the classes.
class FinallyEx
{
public static void main(String[]

args)
{
int a=0,b=0,res;
try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
res=a/b;
System.out.println("Division is:"+res);
}
catch(ArithmeticException e)
{
System.out.println("can not divide by zero");
}
catch

(ArrayIndexOutOfBoundsExceptio

n e)
{
System.out.println("Insufficient

arguments:");
}
finally
{
res=a+b;
System.out.println("Addition

is:"+res);
}
}
}

OUTPUT:
10 5=>Division :2
Addition=>15
10 “ABC”
Addition =>10
--Now in the output we can observe that when second argument is given as string then exception occurs and program is
terminated but still in this case the code written in finally block is executed and result of addition is displayed.
Throws statement/Declaring Exception
--throws keyword is used when we doesn’t want to handle the exception and try to
send the exception to JVM or other method.
--In a program if there is chance of raising an exception then compiler always warn us
about it and we should compulsorily handle that checked exception,otherwise we
will get compile time error saying unreported exception Exception_Name must be
caught or declared to be thrown.
--to prevent this compile time error we can handle the exception in two ways:
1.By using try catch
2.By using throws keyword.
--we can use throws keyword to delegate the responsibilities of exception handling to
the caller (It may be method or the JVM)then caller method is responsible to
handle the exception.
Syntax:
• return_type method_name() throws exception_class_name{
• //method code
• }

--In the previous session we learn while using BufferedReader class.


import java.io.*;
class Throws
{
public static void main(String[]args)throws IOException
{
String nm;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter your name:”);
nm=br.readLine();
System.out.println(“Hello:”+nm);
}
}
OUTPUT:
Enter name:Kunal
Hello:Kunal.
Throwing and Re-throwing an Exception/throw keyword
--The throw keyword in java is used to explicitly throw an exception from a
method or any block of code.
--we can throw either checked or unchecked exception.
--up to we learn when an exception occurs in try block,an object is created
and thrown.
--This object is caught by the matching catch block which then handles the
particular exception.
--Sometimes it may be possible that the catch block may not be able to
handle the exception.
--For example consider a client server application.when an exception occurs
at client side application regarding database (which is present on
server),then the client application can re-throw the exception to server
application which can handle the exception.
--In case the server application is also not able to handle the exception,then it
will be handled by the default java runtime system.
--class test
{
static void divide()
{
int x,y,z;
try
{
x=5;
y=0;
z=x/y;
System.out.println(x+"/"+y+"="+z);
}
catch(ArithmeticException e)
{
System.out.println("Exception Caught in Divide()");
System.out.println("Cannot Divide by Zero in Integer Division");
throw e;
}
}
}
public class RethrowingException
{
public static void main(String[]args)
{
System.out.println("start of main()");
try
{
test.divide();
}
catch(ArithmeticException e)
{
System.out.println("Caught in main:");
System.out.println(e);
}
}
}
Built In Exception
--Java Defines several exception classes inside the standard
package java.lang.
--The most general built in exception are subclasses of the
standard type RuntimeException.since java.lang is implicitly
imported into all java programs,most exception derived from
RuntimeException are automatically available.
--RuntimeException is the superclass of those exceptions that
can be thrown during the normal operation of the Java
Virtual Machine. RuntimeException and its subclasses are
unchecked exceptions.
--Java defines several other types of exceptions that relate to
its various class libraries.Following the list of java Unchecked
Runtime Exception
Exception Description

ArithmeticException Arithmetic error,Such as divide by zero

ArrayIndexOutOfBounds Array index out-of-bounds

ArrayStoreException Assignment to an array element of an


incompatible type.

NumberFormatException Invalid conversion of a string to a numeric


format.

NullPointerExeption Invalid use of a null reference

StringIndexOutOfBounds Attempt to index outside the bounds of a


string.

ClasscastException Invalid cast


Checked Exception
Checked Exception Description

ClassNotfoundException Class not found

IllegalAccessException Attempt to clone an object that does not


implement the clonable interface.

InstantiationException Attempt to create an object of an abstract


class or interface.

InterruptedException One thread has been interrupted by


another thread

NoSuchFieldException A requested field does not exist.

NoSuchMethodException A requested method does not exist.


Chained Exception
--chained Exception allow to relate one exception with
another exception,i.e one exception describes cause
of another exception.
--For example ,consider a situation in which throws an
ArithmeticException because of an attempt to divide
by zero but the actual cause exception was an I/O
error which is caused the divisior to be zero.
--The method will throw only ArithmeticException to
the caller.So the caller would not come to know
about the actual cause of exception.chained
exception is used in such type of situations.
--Constructors of Throwable class which support chained exceptions in java
1.Throwable:(Throwable cause)
2.Throwable(String str,Throwable cause)
--In the first form ,the parameter cause specifies the actual cause of
exception.
--In the second form ,it allows us to add an exception description in string
form with the actual cause of exception.
--getCause() and initCause() are the two methods added to Throwable class.
--getCause()method returns the actual cause associated with current
exception.
--initCause() set an underlying cause(exception)with invoking exception.
import java.io.IOException;
public class ChainedException
{
public static void divide(int a,int b)
{
if(b==0)
{
ArithmeticException ae= new ArithmeticException("top layer");
ae.initCause(new IOException("cause"));
throw ae;
}
else
{
System.out.println(a/b);
}
}
public static void main(String[]args)
{
try
{
divide(5,0);
}
catch(ArithmeticException ae)
{
System.out.println("caught:"+ae);
System.out.println("actual cause:"+ae.getCause());
}
}
}
Creating Own Exception
--Up till now we have seen various built in type of exceptions such Arithmetic
Exception, Array Index Out Of Bounds Exception, Number Format Exception etc.
--Sometimes there may be need to raise an exception as per user requirenment.Such
exception are known as user defined or customized exception.
--There are very simple steps to create user defined exception.if we remember these
steps,we can create any type of user defined exception.
Step 1: Create a user defined class and extends it form Exception class of java.
Step 2:Define a constructor in this class printing an error message for particular
customized exception.
Step 3:In main class define try block.Give call to user defined class constructor if
exception occurs using throw keyword.
Step 4:Define catch block.create object as parameter for user defined class .Write code
to handle the exception.
import java.io.*;
import java.lang.Exception;
class negativeage extends Exception
{
public negativeage()
{
System.out.println("Exception Occurs");
}
}
class ThrowEx1
{
public static void main(String[]args)throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter your name:");
String name=br.readLine();
System.out.println("Enter your age:");
int age=Integer.parseInt(br.readLine());
if(age<0)
throw new negativeage();
else
System.out.println("Thank you...."+name);
}
catch(negativeage e)
{
System.out.println("Age is negative:"+e);
}
}
}
import java.io.*;
import java.lang.Exception;
class NoMatchException extends Exception
{
public NoMatchException()
{
System.out.println("Exception occurs");
}
}
class ThrowEx2
{
public static void main(String[]args)throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter a string:");
String str=br.readLine();
if(!str.equals("MSBTE"))
throw new NoMatchException();
else
System.out.println("Thank you.....");
}
catch(NoMatchException e)
{
System.out.println("String is not in MSBTE");
}
}
}
import java.io.*;
import java.lang.Exception;
class test extends Exception
{
public test()
{
System.out.println("Exception occurs:");
}
}
class ThrowEx4
{
public static void main(String args[])
{
try
{
int len=args.length;
if(len!=2)
throw new test();
else
System.out.println(args[0]+""+args[1]);
}
catch(test e)
{
System.out.println("Invalid parameter Exception:");
}
}
}
import java.io.*;
import java.lang.Exception;
class tempException extends Exception
{
public tempException(String msg)
{
System.out.println(msg);
}
}
class ThreadEx4
{

public static void main(String[]args)throws IOException

{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a float Value:");
float n=Float.parseFloat(br.readLine());

if(n<94)
throw new tempException("Tempreature below normal:");
else if(n>=95 && n<100)
throw new tempException("Normal Tempreature:");
else if(n>100)
throw new tempException("High Tempreature:");
}
catch(tempException e)
{
System.out.println(e);
}
}
}
import java.io.*;
import java.lang.Exception;
class AuthenticationFailure extends Exception
{
public AuthenticationFailure()
{
System.out.println("Invalid Password:");
}
}
class ThrowEx3
{
public static void main(String[]args)throws IOException
{
try
{
String pass;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter password:");
pass=br.readLine();
if(pass.equals("rose"))
System.out.println("Login Successfully");
else
throw new AuthenticationFailure();
}
catch(AuthenticationFailure e)
{
System.out.println(e);
}
}
}
import java.io.*;
import java.lang.Exception;
class checkemail extends Exception
{
public checkemail()
{
System.out.println("Exception occurs:");
}
}
class ThrowsEx15
{
public static void main(String[]args)throws IOException
{

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));
try
{
System.out.println("Enter the email id:");
String eid=br.readLine();
int index=eid.indexOf('@');
if(index==-1||Character.isDigit(eid.charAt(0))) throw new checkemail();
else
System.out.println("Valid email id:");
}
catch(checkemail e)
{
System.out.println("Invalid email id:"+e);
}
}
}
import java.io.*;
import java.lang.Exception;
class OverPriceException extends Exception
{
public OverPriceException()
{
System.out.println("OverPriceException:Price is heavy...");
}
}
class ThreadEx9
{
public static void main(String args[])throws IOException
{
try
{
int itemcode;
String itemname;
Float itemprice;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print("\n Enter item code:");


itemcode=Integer.parseInt(br.readLine());
System.out.print("Enter item name:");
itemname=br.readLine();

System.out.print("enter item price:");


itemprice=Float.parseFloat(br.readLine());

if(itemprice>9999)
throw new OverPriceException();
else
System.out.println(itemcode + " " + itemname + " " + itemprice +" ");
}
catch(OverPriceException e)
{
System.out.println(e);
}
}
}
import java.io.*;
import java.lang.Exception;
class InvalidLogin extends Exception
{
public InvalidLogin()
{
System.out.println("Invalid Login");
}
}
class ThreadEx10
{
public static void main(String args[]) throws IOException
{
try
{
String user,pass;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter user name:");
user=br.readLine();
System.out.print("Enter Password:");
pass=br.readLine();
if(user.equals(pass))
System.out.println("Login Successfully:");
else
throw new InvalidLogin();
}
catch(InvalidLogin e)
{
System.out.println(e);
}
}
}
Difference Between Throw and Throws
Parameter Throw Throws
Use It is used to explicitly throw It is used to declare an
an exception exception.
Checked Exception Checked exception cannot Checked exception can be
be implemented using implemented using throws.
throw only.

Instance or class Throw is followed by Throw is followed by class.


instance
Location Throw is used inside Throws is used with the
definition of a method. signature of a method.

Multiple Exception Multiple exception cannot Multiple exception can be


be thrown by throw declared by throws
keyword keyword
e.g.public void
method()throws
IOException,SQLException.
Multithreading Process
• Multitasking
--Multitasking is a process of executing multiple
tasks simultaneously.we use multitasking to
utilize the CPU completely.
--Multitasking can be achieved in two ways
1.Process-based Multitasking
2.Thread-Based Multitasking
1.Process Based Multitasking
--Multiple tasks are executed simultaneously by
multiple application.
--Each process has an address in memory.In other
words each process allocates a seprate memory
area.
--A process is heavy Weight.
--Cost of Communication between the process is high.
--Switching from one process to another requires some
time of saving and loading registers,memory
maps,upating lists.
Thread Based Multitasking
--Multiple tasks are executed simultaneously by
single application
--Threads share the same address space.
--A thread is lightweight.
--cost of communication between the thread is
low.
--Multithreading in java is a process of executing
multiple threads simultaneously.
Advantages of Multithreading
--Advantages of Multithreading
1.Enhanced performance by decreased
development time.
2.Improvised GUI responsiveness.
3.Simultaneous and parallelized occurrence of
tasks.
4.Decreased cost of maintainance.
5.Better use of CPU resources.
Disadvantages Of Multithreading
--Complex debugging and test processes.
--Overhead switching of context.
--Increased potential for deadlock occurrence.
--Increased difficulty level in writing a program.
--unpredictable results.
Life Cycle of Thread
--A thread goes through different stages in its life cycle.For example,a thread
is born,started,runs,and finally dies.

yield()
Runnable Running

sleep () stop() run method over


Start() wait() notify()
Suspend() resume()
sleep time over Dead
New born
stop()

Blocked stop()
--Thread is lightweight sub-process,the smallest unit of processing.
New
--Whenever a new thread is created, it is always in the new state. For a thread in the
new state, the code has not been run yet and thus has not begun its execution.
--it remains in this state until the program starts the thread using its start () method.
Syntax::
public static final Thread.State NEW
--When a thread invokes the start() method, it moves from the new state to the active
state. The active state contains two states within it: one is runnable, and the other
is running.
Runnable
--A thread, that is ready to run is then moved to the runnable state. In the runnable state,
the thread may be running or may be ready to run at any given instant of time. It is the
duty of the thread scheduler to provide the thread time to run, i.e., moving the thread
the running state.
--A program implementing multithreading acquires a fixed slice of time to each individual
thread. Each and every thread runs for a short span of time and when that allocated
time slice is over, the thread voluntarily gives up the CPU to the other thread, so that
the other threads can also run for their slice of time. Whenever such a scenario occurs,
all those threads that are willing to run, waiting for their turn to run, lie in the runnable
state. In the runnable state, there is a queue where the threads lie.
--public static final Thread.State RUNNABLE
--It represents the runnable state.It means a
thread is waiting in the queue to run.
Running state
--In most operating system,each thread is given a
small amount if processor time called a
quantumnor slice to perform its task.
--A thread utilizing its quantum is said to be in
RUNNING state.When its quantum expires,the
thread returns to RUNNABLE state,and the
Operating System assigns another thread to the
processor.
Blocked/Waiting
--A thread enters a waiting state in three
situations:
1.When a thread has called wait() method on
itself and is waiting for other thread to notify
it or wake up.
2.When a thread code has called sleep() method
on a thread asking it to sleep for duration.
3.When a thread is waiting for an Input/Output
resources to be free.
Dead State
--This is considered as last state in thread’s lifecycle.
--A thread enters the dead state after it has successfully
completed executing the run() method.
--At this situation it is considered to be not alive and hence it
cannot be restarted again.
Main Thread
--when execution of java program begins,one thread starts
executing immediately.it is known as the main thread of
program.
--The main thread is important for two reasons:
1)Support child threads
2)Usually it will be last thread to finish execution because it
has to perform several shutdown actions.
--Even though the main thread is created
automatically,to handle it have to create a
Thread Object.for this purpose we must obtain
a reference it to by calling the methid
currentThread(),which is public static member
of thread.
--static Thread currentThread()
--this method returns a reference to the thread
in which it is called.
class ThreadEx1
{
public static void main(String[]args)
{
Thread t=Thread.currentThread();
System.out.println("Current Thread:"+t);
t.setName("My Thread:");
System.out.println("After Name changed:"+t);
try
{
for(int n=5;n>0;n--)
{
System.out.println("\t"+n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Thread Interrupted:");
}
}
}
Creating Thread

• As we have seen ,By default java provides a ready main thread.But want to
create our own threads then there are two options:
1.By implementing Runnable Interface
2.By extending Thread Class
1.By implementing Runnable Interface
--This is simple option to create Thread.
--Runnable Interface has declared an abstract method run(),which we have to
override(define)in the child class.
--The code of run() method is considered as code of thread.
--The run() method can call other methods ,use other classes and declare
variables,just like main thread can .
--after implementing runnable by a class we can instantiate an object of type
Thread.
class Demo implements Runnable
{
Thread th;
Demo()
{
th=new Thread(this,"Demo");
System.out.println("Chid Thread:"+th);
th.start();
}
public void run()
{
try
{
for(int n=5;n>0;n--)
{
System.out.println("\t Child thread:"+n);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("child Thread interrupted");
}
System.out.println("child Execution completed:");
}
}
class ThreadEx2
{
public static void main(String []args)
{
new Demo();
try
{
for(int n=15;n>10;n--)
{
System.out.println("Main Thread:"+n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Error.......interrupted:");
}
System.out.println("Main Thread Execution Completed");
}
}
BY implementing Extending Thread class

--Another option to create a thread is to create


new class which extends Thread class of java
--we have to override the run()abstract method
in the child class which is entry point for the
new thread.
--Also we have to call start() method to begin
execution of new thread.
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<6;i++)
System.out.println(i+”\t”);
}
}
class ThreadEx6
{
public static void main(String[]args)
{
MyThread t=new MyThread();
System.out.println(t);
t.start();
}
}
Thread Methods
1.wait()
--Tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify().
2.notify()
--Wakes up thread that called wait() on same object.
3.notifyAll()
--Wakes up all the threads that called wait() on the same object,one of the
threads will be granted access.
4.sleep()
--This method causes the currently executing thread to sleep for the
specified number of miliseconds,subject to the precision and accuracy of
system timers and schedulars.
5.public void suspend()
--This method puts a thread in the suspend state and
can be resumed using resume() method.
6.public void resume()
--this method resumes a thread,which was
suspended using suspend() method.
7.public void stop()
--This method stops a thread completely.
8.public static void yield()
--This method causes the currently executing thread
object to temporarily pause and allow other
threads to execute
Thread Exception
--In multithreading usually the methods which
halts the execution of thread such as
sleep(),wait() etc.are written in try block.
--if any exception occurs it would be caught by
catch block which creates object of class
InterruptedException as parameter.
try
{
for(int n=5;n>0;n--)
{
System.out.println(“\t”+n)
thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(“Thread Interrrupted”);
}
Thread Priority and methods
• In a multithreading environment,thread scheduler assigns processor to a
thread based on priority of thread.
• To create java Thread it always some priority can be given through JVM or
Programmer Expilicitly.
• Standard priority value is 1 to 10.
• Public static int MIN_PRIORITY:
This is minimum priority that thread can have value of 1.
• Public static int NORM_PRIORITY:
This is default priority of thread if do not expilicitly define it. value of 5.
• Public static int MAX_PRIORITY:
This is maximum priority that thread can have value of 10.
Methods of thread Priority

--public final int getPriority()


Java.lang.Thread.getPriority()
--This methods return priority of associated Thread.
--public final int setPriority()—(int new Priority)
Java.lang.Thread.setPriority()
--This methods changes the priority of thread to
the value newPriority.
--it throws IllegalArgumentsException if value of
parameter newPriority goes beyond the range (1-
10).
class Thread
{
public static void main(String[]args)
{
Thread d=Thread.currentThread();
Int p=d.getPriority();
System.out.println(“Default priority:”+p);
d.setPriority(10);
p=d.getPriority();
System.out.println(“new Priority:”+p);
}
}
Synchronization
--As we know multithreading number of threads are running
simultaneously.
--These threads may share same resources such as
database,images,methods etc.
--just consider a thread is accessing a resources and meanwhile another
thread try to access the same resources,then some irrelevant outputs
may generate.
--To avoid this problem java provides concept sychronization,in which
when a thread is accessing any specific resources,then we can lock
that resource for all the other threads unless the first thread leaves
its access.
--key to synchronization is the concept of the monitor.
--A monitor is an object that is used as a mutually exclusive lock.
--only one thread can own a monitor at a given
time.when a thread acquires a lock,it is said to
have entered the monitor.
--All other threads attempting to enter the
locked monitor will be suspended until the
first thread exists the monitor.
--These other threads are said to be waiting for
the monitor .A thread that owns a monitor
can re-enter the the same monitor if it so
desires.
import java.lang.Exception;
import java.io.*;
class class1
{
void method(String data)
{
System.out.println("["+data);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class class2 implements Runnable
{
String data;
class1 target;
Thread t;
public class2(class1 targ,String s)
{
target=targ;
data=s;
t=new Thread(this);
t.start();
}
public void run()
{
target.method(data);
}
}
class threadEx6
{
public static void main(String args[])
{
class1 target=new class1();
class2 ob1=new class2(target,"Hello");

class2 ob2=new class2(target,"Kunal");


class2 ob3=new class2(target,"How are you?");

try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
class threadEx6
{
public static void main(String args[])
{
class1 target=new class1();
class2 ob1=new class2(target,"Hello");

class2 ob2=new class2(target,"Kunal");


class2 ob3=new class2(target,"How are you?");
import java.io.*;
import java.lang.Exception;
class class1
{
synchronized void method(String data)
{
System.out.print("["+data);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class class2 implements Runnable
{
String data;
class1 target;
Thread t;
public class2(class1 targ,String s)
{
target =targ;
data=s;
t=new Thread(this);
t.start();
}
public void run()
{
target.method(data);
}
}
class ThreadEx7
{
class1 target=new class1();
class2 ob1=new class2(target,”Hello”);
class2 ob2=new class2(target,”kunal”);
C
.lass2 ob3=new class2(target,”How r u”);
public static void main(String atgs[])
{
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
--Now here we can observe that even when execution of first thread stopped for 1 second,the access of method
is not granted to another thread unless execution of first thread gets completed.
Inter thread Communication

--In multithreading sometimes output generated by one


thread acts as input for another thread.And when the
output used by second thread,the first thread has to
generate another output.
--here the question is how second thread will come to know
that the first thread has created new output and also how
first thread will know that the output generated by it is
used by second thread.
--for this purpose in initial days,concept of polling was used
in which a continues loop was running to check the
values.But this waste many CPU cycles and makes the
implementation inefficient.Hence java gives the solution
of inter thread Communication.
--To avoid polling,Java uses three
methods,namely,wait(),notify() and notifyAll().
--consider two threads;producer and
consumer.Consider an integer variable n and
boolean variable valueSet.
--Work of producer is to set new value to n and
true to valueset.The consumer will utilize
value of n and set value of valueset to false.
class class1
{
int n;
boolean valueSet=false;
synchronized void put_value(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
this.n=n;
valueSet=true;
System.out.println("\t put_value:"+n);
notify();
}
synchronized int get_value()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return(n);
}
}
class Producer implements Runnable
{
class1 obj;
Producer(class1 obj){
this.obj=obj;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
obj.put_value(i++);
}
}
}
class Consumer implements Runnable
{
class1 obj;
Consumer(class1 obj)
{
this.obj=obj;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
obj.get_value();
}
}
}
class ThreadEx8
{
public static void main(String[]args)
{
class1 obj=new class1();
new Producer(obj);
new Consumer(obj);
System.out.println("Press Control-C to stop");
}
}
Deadlock
--Deadlock is problematic concept in multithreading.deadlock can occur in a certain
circumstances when a thread (say T1)is waiting for an object lock,which is acquired
by another thread(say T2)and second thread (T2)is waiting for an object lock which
is acquired by first thread(T1).
--As both of the threads are waiting for each other to release the lock daadlock occurs.
--The main reason behind deadlock condition is the sychronized keyword which causes
the executing thread to a block while waiting for the lock,or monitor,associated
with the specified object.

Rsrc-A

Thread-2 Thread-1

Asrc-A
import java.io.*;
import java.lang.Exception;

public class DeadLock


{
public static Object FirstLk=new Object();
public static Object SecondLk=new Object();
public static void main(String args[])
{
Class2 THREAD1=new Class2();
Class3 THREAD2=new Class3();
THREAD1.start();
THREAD2.start();
}
private static Class2 extends Thread
{
public void run()
{
synchronized(FirstLk)
{
System.out.println("Thread 1:Holding lock 1....");
try
{
Thread.sleep(10);
}
catch(InterruptedException e)
{
}
System.out.println("Thread 1:Waiting for lock 2....");
synchronized(SecondLk)
{
System.out.println("Thread 1:Holding lock 1 & 2....");
}
}
}
}
private static class Class2 extends Thread
{
public void run()
{
synchronized(FirstLk)
{
System.out.println("Thread 1:Holding lock 1....");
try
{
Thread.sleep(10);
}
catch(InterruptedException e)
{
}
System.out.println("Thread 1:Waiting for lock 2....");
synchronized(SecondLk)
{
System.out.println("Thread 1:Holding lock 1 & 2....");
}
}
}
}

You might also like