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

Unit E28093 5 - Exception Handling Multithreaded Programming

The document discusses exception handling and multithreading in Java. It covers types of errors like compile-time errors and runtime errors. It describes common exceptions like ArithmeticException, NullPointerException, and ArrayIndexOutOfBoundsException. The key aspects of exception handling are discussed, including using try, catch, and throw statements to detect and handle exceptions. Multithreading concepts like creating and running threads are also mentioned.

Uploaded by

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

Unit E28093 5 - Exception Handling Multithreaded Programming

The document discusses exception handling and multithreading in Java. It covers types of errors like compile-time errors and runtime errors. It describes common exceptions like ArithmeticException, NullPointerException, and ArrayIndexOutOfBoundsException. The key aspects of exception handling are discussed, including using try, catch, and throw statements to detect and handle exceptions. Multithreading concepts like creating and running threads are also mentioned.

Uploaded by

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

UNIT:5

EXCEPTION HANDLING &


1

MULTITHREADED
TOPICS TO BE COVERED…
5.1 Types of errors
 Exceptions
 try..catch statement
 Multiple catch blocks
 Throw and Throws keywords
 finally clause
 Uses of exceptions
 User defined exceptions

2
TOPICS TO BE COVERED………
5.2
 Creating thread
 Extending thread class
 Implementing Runnable interface
 Life cycle of thread
 Thread priorities
 Thread Synchronization
 Exception handling in threads

3
5.1 INTRODUCTION
 It is common to make mistakes while developing or
in typing a program. A mistake leads to an error
causing the program to produce unexpected results
 .Errors are the wrongs that can make a program to
produce unexpected / unwanted output.
 Error may produce
 - an incorrect output
 - may terminate the execution of program
abruptly
 - may cause the system to crash
 It is important to detect and manage properly all
the possible error conditions in program.
4
TYPES OF ERRORS
 Compile time Errors:
Detected by javac at the compile time
 Run time Errors:
Detected by java at run time

5
COMPILE TIME ERRORS(SYNTACTICAL
ERRORS)

 Errors which are detected by javac at the


compilation time of program are known as compile
time errors.
 Most of compile time errors are due to typing
mistakes, which are detected and displayed by
javac.
 Whenever compiler displays an error, it will not
create the .class file.
 So it is necessary to fix all the errors before we can
compile and run the program.

6
COMPILE TIME ERRORS(SYNTACTICAL
ERRORS)

 A single error may be the source of multiple


errors.
 We should solve the earliest error in program.
After fix an error ,recompile the program and
look for other errors.
 Typographical errors are hard to find.

7
THE MOST COMMON PROBLEMS:
 Missing semicolon
 Missing or mismatch of brackets in classes and
methods
 Misspelling of identifiers and keywords
 Missing double quotes in strings
 Use of undeclared variables
 Incompatible types in assignments/ Initialization

8
THE MOST COMMON PROBLEMS:

 Bad references to objects


 Use of = in place of = = operator
 And so on…
 Other errors are related to directory path. Errors
such as
 javac :command not found
 means we have not set path correctly where java
executables are stored.

9
EXAMPLE OF COMPILE TIME ERROR
class Error1
{
public static void main(String args[])
{
System .out.println(“Hello”) //
Missing ;
}}
javac detects an error and display it as
follow:
Error1.java : 5 : ‘ ; ‘ expected
System.out.println(“Hello)
^1 error 10
RUN TIME ERRORS (LOGICAL ERRORS)
 There is a time when a program may compile
successfully and creates a .class file but may not
run properly.
 It may produce wrong results due to wrong logic
or may terminate due to errors like stack
overflow, such logical errors are known as run
time errors.
 Java typically generates an error message and
aborts the program.
 It is detected by java (interpreter)
 Run time error causes termination of execution of
the program.
11
THE MOST COMMON RUN TIME ERRORS ARE:
 Dividing an integer by zero.
 Accessing element that is out of the bounds of an
array.
 Trying a store a value into an array of an
incompatible class or type.
 Trying to cast an instance of a class to one of its
subclasses.
 Passing a parameter that is not in a valid range or
value for a method.

12
THE MOST COMMON RUN TIME ERRORS ARE:
 Trying to illegally change the state of a thread.
 Attempting to use a negative size of an array
 Using a null object reference as a legitimate object
references to access a method or a variable.
 Converting invalid string to a number.
 Accessing a character that is out of bounds of a
string And many more.

13
EXAMPLE OF RUNTIME ERROR
class Error2
{
public static void main(String args[])
{
int a=10,b=5 ,c=5;
int x = a / (b-c); // division by zero
System.out.println(“x=“ + x);
int y = a / (b+c);
System.out.println(“y=“ + y);
}
}
14
EXAMPLE OF RUNTIME ERROR
 This code is syntactically correct ,therefore does not
cause any problem during compilation.
 While executing it displays following message and
stops without executing further statement.

java.lang.ArithmeticException : / by Zero
at Error2.main(Error2.java:6)

15
COMPILE TIME VS. RUNTIME ERRORS
Compile time error Run time error

 Definition  Definition
 Detected at compile  Detected at Run time
time  Java interpreter finds
 Javac (java compiler) such errors
detects such errors  Logical error
 Syntactical error  .class file will be
 If it occurs .class file there before error
will be not created occur.
16
EXCEPTIONS
 An Exception is abnormal condition that is caused by
a runtime error in the program.
 When java interpreter encounters an error such as
dividing by zero ,it creates an exception object and
throws it.
 If the exception object is not caught and handled
properly ,the interpreter will display an error
message and will terminate the program.
 If we want to the program to continue with the
execution of remaining code, then we should try to
catch exception object thrown by the error condition
and then display an appropriate message for taking
corrective actions. this is known as Exception
handling. 17
EXCEPTIONS
 The purpose of exception handling is to provide a
means to detect and report an “exceptional
circumstances “ so we can take proper actions.
 Error handling code consist of two segments
1) detect errors and to throw exceptions
2) catch the exceptions and take appropriate actions
 This mechanism performs following tasks in
sequence.
 Find the problem (Hit the Exception).
 Inform that an error has occurred (Throw the
Exception).
 Receive the error information catch the exception)
 Take corrective actions (Handle the Exception). 18
COMMON JAVA EXCEPTIONS
SR Exception Type Cause of Exception
NO.

1 ArithmeticException Caused by math error such as


divide by zero
2 ArrayIndexOutOfBoundsEx Caused by bad array indexes
ception
3 ArrayStoreException Caused when a program tries to
store the wrong type of data in
an array
4 FileNotFoundException Caused by an attempt to access
a nonexistent file
5 IOException Caused by general I/O failures,
such as inability to read from a
file 19
COMMON JAVA EXCEPTIONS
SR Exception Type Cause of Exception
NO.

6 NullPointerException Caused by referencing a null


object
7 NumberFormatException Caused when a conversion
between strings and number
fails
8 OutOfMemoryException Caused when there’s not enough
memory to allocate a new object
9 SecurityException Caused when an applet tries to
perform an action not allowed by
the browser’s security
20
COMMON JAVA EXCEPTIONS
SR Exception Type Cause of Exception
NO.

9 StackOverflowException Cause when the system


runs out of stack space
10 StringIndexOutOfBoundsExceptio Caused when a program
n attempts to access a
nonexistent character
position in a string

21
SYNTAX OF EXCEPTION HANDLING CODE

 The basic concept of Exception handling are throwing


an exception and catching it.

try Block
Exception
Statement that object creator
causes an
exception
Throw
exceptio
n catch Block
object
Exception
Statement that
Handler
handles the
exception 22
Fig. : Exception handling mechanism
TRY BLOCK
 Java uses a try block defined by keyword try.
 try block contain block of code that causes an error
condition and throw an exception.
 try block can have one or more statements that
could be generate an exception.
 If any one statement generates an exception than
remaining statements in block are skipped and
execution jumps to the catch block that is placed
next to try block.
 Every try statement should be followed by at least
one catch statement; otherwise compilation error
will occur.

23
CATCH BLOCK
 Java uses a catch block defined by keyword catch.
 catch block “catches” the exception “thrown” by the
try block and handles it appropriately.
 catch block too can have one or more statements
that are necessary to process the exception. The
catch block is added immediately after the try block.
 catch statement works like a method definition. It is
passed as single parameter which is reference to the
exception object thrown.
 If catch parameter matches with the type of
exception object, then exception is caught and that
catch block will be executed.
 If catch parameter does not match with any type of
exception then default exception handler will cause
24
the execution to terminate.
SYNTAX OF TRY –CATCH BLOCK
…………………………………
…….................................
try
{
Statement; //generates an exception an
throw it
}
catch(Exception-type e)
{
Statement; // catch and processes the
exception
} 25
…………………….
EXAMPLE -1
class Error3
{ public static void main(String args[])
{
int a=10,b=5,c=5;
int x,y;
try
{
X=a / (b-c); //Exception here
}
catch(ArithmeticException e)
{
System.out.println(“division by zero”);
}
Y= a / (b +c );
System.out.println(“y=”+y);}} 26

Continue………
EXAMPLE -1
Output:
Division by zero
y=1

Here, The program did not stop at the point of


exceptional condition .It catches the error condition
,prints the error message and then continues the
execution .

27
EXAMPLE 2: TRY –CATCH BLOCK
class ClineInput
{
public static void main(String args[])
{
int invalid =0;
int num,count=0;
for ( int i=0; i< args.length ; i++)
{
try
{
num= Integer.parseInt( args[i]);
}
28
Continue………
EXAMPLE 2: TRY –CATCH BLOCK
catch ( NumberFormatException e)
{
invalid =invalid + 1;
System.out.println (“Invalid Number:” +args[i]);
continue;
}
count = count +1;
}
System.out.println (“Valid Numbers =” + count);
System.out.println (“Invalid Numbers=“+ invalid );
}
}
Continue……… 29
EXAMPLE 2: TRY –CATCH BLOCK
When we run the program with the command line :
javac ClineInput.java
java Cline Input 15 28.2 java 10.5 65

Output:
Invalid Number : 28.2
Invalid Number : java
 Invalid Number : 10.5

 Valid Number : 3

 Invalid Number : 2

30
MULTIPLE CATCH STATEMENTS
Syntax:
try
{
Statement; // generates an exception
}
catch(Exception-type-1 e)
{
Statements ; // processes exception type 1
}
catch(Exception-type-2 e)
{
Statements ; // processes exception type 2
}
catch(Exception-type-N e)
{
Statements ; // processes exception type N
} 31
MULTIPLE CATCH STATEMENTS
 In case of multiple catch statements they are treated
as switch statement.
 The first statement whose parameters matches with
the exception object will be executed and remaining
statements will skipped.
 Java does not require any processing of the exception
at all.
 We can use catch statement with an empty block to
avoid program abortion.
 e.g. catch (Exception e);
Or
catch (Exception e)
{
}
 This statement will perform anything, it catch an 32
exception and then ignore it.
EXAMPLE
class Error4
{
public static void main(String args[])
{
int a [ ]= {5,10};
int b=5;
try
{
int x = a[2] / b – a[1];
}
catch (ArithmeticException e)
{
System.out.println (“Division by zero”);
}
33
Continue…..
EXAMPLE
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println (“Array index error”);
}
catch(ArrayStoreException e)
{
System.out.println (“Wrong data type”);
}
int y= a[1] / a[0];
System.out.println (“y= “+y);
}
34
} Continue…..
EXAMPLE

Output:
Array index error
Y=2

Note: When exception object matches to any catch


block, it will catch and handle the error.
Remaining catch blocks are skipped.

35
USE OF FINALLY STATEMENT
 finally statement can be used to handle an exception
that is not caught by any of the previous catch
statements.
 finally block can be used to handle any exception
generated within a try block.
 It may be added immediately after try block or after
the last catch block.
 When finally block is defined, this is guaranteed to
execute, regardless of whether or not an exception is
thrown.
 finally statement used to perform operation like
closing files and releasing system resources.

36
try try
{
{
………..
………….. }
………….. (1) catch(…….)
} {
finally …………….
}
{
catch (…….)
………………. {
……………... ………..
} (2) }
.
.
finally
We can use finally in this two {
way.. ……………
37
}
EXAMPLE: TRY –CATCH –FINALLY BLOCK
class Error4
{
public static void main(String args[])
{
int a [ ]= {5,10};
int b=5;
try
{
int x = a[2] / b – a[1];
}
catch (ArithmeticException e)
{
System.out.println (“Division by zero”); 38

} Continue…..
EXAMPLE: TRY –CATCH –FINALLY BLOCK
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println (“Array index error”);
}
catch(ArrayStoreException e)
{
System.out.println (“Wrong data type”);
}
finally
{
int y=a [1] /a[0];
System.out.println( “y =” +y); 39

}}}
EXAMPLE: TRY –CATCH –FINALLY BLOCK
OUTPUT :
Array index error
Y=2

40
NESTED TRY-CATCH BLOCK
 Nested try statement means that try statement
within a block of another try.
 If a inner try statement does not have a catch
handler for a particular exception, then next try
statement's catch handlers are inspected for a
match.
 This continues until one of catch statements
succeeds and until all of nested try { } statements
are exhausted.
 If no catch statements matches then the Java-run
time system will handle the exception.

41
EXAMPLE
class nested_try
{
public static void main(String args[])
{
try
{
int a=2,b=4,c=2,x=7,z;
int p[]={2};
p[3]=33;
try
{
z=x/ (b*b) - (4*a*c);
System.out.println(“The value of z is =“ +z);
}
42
EXAMPLE
catch (ArithmeticException e)
{
System.out.println("Division by zero in Arithmetic
expression");
}}

catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index is out-of-
bounds");
}
}
}

Output:
Array index is out-of bound. 43
TYPES OF EXCEPTION
 All types of exceptions are subclasses of built in class
Throwable.
 Throwable class is contained in java.lang package.
 Errors are thrown by any methods of Java API or by
java virtual machine.
 Exception is a super class of all types of exceptions.
 When we use multiple catch statements ,exception
subclasses must come before any of their super
classes because catch statement that uses a super
class will catch exception of that type plus any of its
subclass.
 Thus, a subclass would never be reached if it came
after its subclass, it will give unreachable code.
44
Throwable

Super class Exception Error

Sub classes

Interrupted Runtime Checked


Exception Exception Exception
(

ArithmeticException NullPointerException ClassCastException

Fig. Java Exception hierarchy


45
THROWING OWN EXCEPTION
 We can make a program to throw an exception
explicitly using throw statement.
throw throwableInstance;
 throw keyword throws a new exception.
 An object of class that extends throwable can be
thrown and caught.
 Throwable  Exception  MyException
 The flow of execution stops immediately after the
throw statement ;
 Any subsequent statements are not executed. the
nearest enclosing try block is inspected to see if it has
catch statement that matches the type of exception.
 If it matches, control is transferred to that statement
 If it doesn’t match, then the next enclosing try
statement is inspected and so on. If no catch block is
matched than default exception handler halts the 46
program.
CREATE JAVA’S STANDARD EXCEPTION
OBJECTS

Syntax:
throw new thowable_instance;
Example:
throw new ArithmeticException();
throw new MyException();
Here ,new is used to construct an instance of
MyException().

47
CREATE JAVA’S STANDARD EXCEPTION
OBJECTS

 All java’s runtime exception s have at least two


constructors:
1) One with no parameter
2) One that takes a string parameter.
In that the argument specifies a string that describe
the exception. this string is displayed when object as
used as an argument to print() or println() .

It can also obtained by a call to getMessage(),a method


defined by Throwable class
48
EXAMPLE
import java.lang.Exception;
class MyException extend Exception
{
MyException (String message )
{
super (message);
}
}
class TestMyExcception
{
public static void main (String args[])
{
int x=5, y=1000;
try
49
{
float z=(float) x/ (float) y;
EXAMPLE
if (z < 0.01)
{
throw new MyException (“Number is
too small”);
}
}
catch (MyException e)
{
System.out.println (“Caught my exception”);
System.out.println (e.getMessage());
}
finally
{
System.out.println (“ I AM ALWAYS HERE”);
}}}
50
EXAMPLE
Output:
Caught my exception
Number is too small
I am always here

51
THROWS
• Throws keyword declares that a method may throw
particular exception.
• If method is capable of causing an exception that it
does not handle.
• It must specify this behavior so that callers of that
method can guard themselves against that exception.
• We can do this by including throws class in the
methods declaration as follows.
Syntax:
type method-name (parameter list ) throws Exception list
{
// body
52
}
EXAMPLE
class ThrowsDemo
{
static void throwone() throws IllegalAccessException
{
System.out.println (“Inside throwone”);
throw new IllegalException (“demo”);
}
public static void main (String args[]);
{
try
{
throwone();
}
catch (IllegalAccessException e)
{ 53
System.out.println (“caught”);}}}
EXAMPLE
Output
Inside throw one
Caught

54
USING EXCEPTION FOR DEBUGGING
• Exception handling mechanism can be used to
hide errors from rest of the program.
• Exception handling mechanism may be
effectively used to locate the type and place of
errors.

55
5.2 MULTI THREADING

56
INTRODUCTION
 Program is a sequence of statements.
 A Program may be divided into two or more sub
programs ,this sub programs are called process.
 Many Processes can be implemented at the same time
in parallel (parallel Execution).
 Process can be divided into further small parts in its
sub process(threads).
 That sub-process is called Thread.

 We can say “Thread” is a smallest unit of a program.

57
IMPORTANT TERMS
 Multiprogramming: More than one program running
at same time. That can share same Processor.
 Multiprocessing :two or more processes of a
program running at same time. They can process on
the own (different) memory location.
 Multithreading: two or more thread of a process
executing in parallel. That can share same memory
location in the memory.
 Multitasking: multiple task performed at a time.

58
THREAD BASED VS. PROCESS BASED MT
Thread based multitasking Process based multitasking

o Single program can o Process based


perform two or more task multitasking allows your
simultaneously. computer to run two or
more program.
o In thread based
multitasking thread is the o Program is smallest unit of
smallest unit of code. code that can be
dispatched by
multitasking.
o Process is dividing into
number of threads. (light
weight process) o Program is divided into
number of processes.
59

Continue……
Thread based multitasking Process based multitasking

o Each thread of same o it’s a heavy weight process.


process shared the same .Each processes have
state, same memory space independent execution
and can communicate with units that contain their
each other directly. because own state information,
they share same variable. address spaces, and
interact with each other via
IPC.
o E.g. Text editor can format
text a t the same time that o E.g. You can run java
it is printing that compiler at the same time
document. these two that you are using a text
actions are being editor.
performed by two separate 60

thread.
SINGLE THREADED PROGRAMS
 A program which has single flow of execution are
single threaded programs.
 When execute a such program ,program begins, runs
through a sequence of execution and finally ends.
 All main programs in our earlier examples are single
threaded programs.
 Every program will have at least one thread .

61
SINGLE THREADED PROGRAM

class ABC
{
………………… Start
…………………
…………………
…………………
………………… Single threaded
………………… body of execution
…………………
…………………
…………………
…………………
…………………
………………… End
}

62
MULTITHREADING CONCEPT
 Multithreading is a conceptual programming
paradigm where a program( or process) is divided
into two or more subprograms( or process),which can
be implemented at the same time in parallel.
 Java enables us to use and manage multiple flows of
control in developing programs.
 Each flow of control may be thought of as a separate
tiny program ,which is known as thread that runs in
parallel to others threads of the same process.
 Threads in java are subprograms of main application
program and share the same memory space, they are
known as light weight process.
63
A MULTITHREADED PROGRAMMING
Main Thread

Main method
module

start start start

switchin switchin
g g

64

Thread A Thread B Thread C


 Once any thread of the process initiated then the
remaining threads run concurrently and share the
same resources jointly.
 Multithreading is similar to dividing a task into
subtasks and assigning them to different people for
execution independently and simultaneously, to
achieve a single desire.
 E.g. In animation ,one sub program can display an
animation on the screen while another may build the
next animation to be displayed.
 Threads are extensively used in java enabled browsers
such HotJava. These browsers can download a file to
the local computer ,display a web page in the window,
output another web page to a printer and so on.
65
 If we are working on any application that requires two
more things to be done at the same time, then threads
are best to use.
Note:
 Actually ,we have only one processor and therefore in
reality the processor is doing only one thing at time.
However , the processor switches between the
processes so fast that it appears to all of them are
being done simultaneously .
 threads running in parallel does not really mean that
they actually run at the same time. Actually ,all
threads are running on a single processor ,the flow of
execution is shared between threads.
 Java interpreter handles the switching of control
between the threads in such a way that it appears
they are running concurrently. 66
Use
 It enables programmers to do multiple things at one
time.
 We can divided a long program into threads and
execute them in parallel, so we can use each and every
resources efficiently.
 We can send tasks into background and continue to
perform some other task in the foreground. This
increase speed of our program.
Example
 Java program with four threads, one main and three
others. here main thread is designed to create and
start the other three threads namely A,B and C.

67
CREATE A THREAD
 We can create a thread by instantiating an object of
type Thread.
 The run() method is the heart and soul of any thread.
 It makes up the entire body of a thread and is the only
method in which the thread’s behavior can be
implemented.

Syntax:
public void run()
{…………
………… (statement for implementing thread)
…………
68
}
CREATE THREAD
 The run() method should be invoked by an object
of concerned thread. For that we have to create
thread and initiate it with the help of other
thread method called start().
 Java can create a thread by following two way:

1) You can implement the Runnable interface.


2) You can extend the Thread class.

69
WHICH ONE OF ABOVE WE SHOULD USE?
 The thread class defines several methods that can be
overridden by a derived class .but only one must be
overridden is run().
 This is, the same method required when we implement
Runnable.
 Many Java programmers feel that classes should be
extended only when they are being enhanced or
modified in some way.
 So it is probably best to implement Runnable instead
of extend Thread class.

70
IMPLEMENTING THE ‘RUNNABLE’ INTERFACE
 The Runnable interface declares the run() method that is
required for implementing threads in our programs.
 To do this ,perform following steps:

1. Declare the class as implementing the Runnable


interface.
2. Implement the run() method.
3. Create a thread by defining an object that is
instantiated from this “runnable” class as the target of
the thread.
4. Call the thread’s start() method to run the thread.
71
EXAMPLE:
class X implements Runnable //step1
{
public void run() //step2
{
for (int i=0; i<=10;i++)
{
System.out.println (“\t ThreadX :” + i );
}
System.out.println(“End of ThreadX”);
}
}
72
EXAMPLE
class RunnableTest
{
public static void main(String args[])
{
X runnable =new X;
Thread threadX= new Thread (runnable); //step3

threadX.start(); // step4
System.out.println(“End of main Thread”);
}
}
73
Output:
End of main Thread
ThreadX : 1
ThreadX : 2
ThreadX : 3
ThreadX : 4
ThreadX : 5
ThreadX : 6
ThreadX : 7
ThreadX : 8
ThreadX : 9
ThreadX : 10
74
End of ThreadX
EXTENDING THE THREAD CLASS
 The Thread class declares the run() method that is
required for overriding threads in our programs. We
can make our class runnable by extending the class
java.lang.Thread.
 To extend Thread class ,perform following steps:

1. Declare the class as extending the Thread class.

2. Implement the run() method that is responsible for


executing the sequence of code that the thread will
execute.
3. Create a thread object and call the start() method to
initiate the thread execution .

75
STEP 1: DECLARING THE CLASS

Thread class can be extended as follows:


class MyThread extends Thread
{
………..
………..
} ,now we have new type of thread MyThread.

76
STEP 2: IMPLEMENTING THE RUN()
INTERFACE
The run() method has been inherited by the class
MyThread. We have override this method to implement
the code executed by our thread.
public void run()
{
……….. //Thread code here
}

When we start the new thread, java calls the thread’s


run() method ,so it is the run() where all the actions
takes place.
77
STEP3: STARTING NEW THREAD
To actually create and run an instance of our thread
class, We must write :
MyThread aThread =new MyThread();
aThread .start(); //invokes run() method
 First line instantiate a new object of class MyThread.

It will just create object ,the thread that will run this
object is not yet running. The thread is in newborn
state.
 Second line calls the start() method causing the thread
to move into runnable state.
Then java runtime will schedule the thread to run
by invoking its run() method.
now thread is said to be in the running state. 78
EXAMPLE OF USING THREAD CLASS
class A extends Thread //step1
{
public void run( ) //step2
{
for (int i=1; i<=5;i++)
{
System.out.println(“\t from Thread A : i =”+i);
}
System.out.println(“Exit from A”);
}

Note: new A().start();


It is equivalent to :A threadA =new A(); 79

threadA.start();
EXAMPLE OF USING THREAD CLASS
class B extends Thread
{
public void run( )
{
for (int j=1; j<=5;j++)
{
System.out.println(“\t from Thread B : j
=”+j);
}
System.out.println(“Exit from B”);
}
80
EXAMPLE OF USING THREAD CLASS
class C extends Thread
{
public void run( )
{
for (int k=1; k<=5;k++)
{
System.out.println(“\t from Thread C : k
=”+k);
}
System.out.println(“Exit from C”);
} 81
EXAMPLE OF USING THREAD CLASS
class ThreadTest
{
public static void main(String args[])
{
new A().start(); //step3
new B().start();
new C().start();
}
}
82
Output:
First run From Thread A : i = 1
From Thread A : i = 2
From Thread B : j = 1
From Thread B : j = 2
From Thread C : k = 1
From Thread C : k = 2
From Thread A : i = 3
From Thread A : i = 4
From Thread B : j = 3
From Thread B : j = 4
From Thread C : k = 3
From Thread C : k = 4
From Thread A : i = 5
Exit form A
From Thread B : j = 5
Exit from B
From Thread C :k = 5 83
Exit from C
Second run From Thread A : i = 1
From Thread A : i = 2
From Thread C : k = 1
From Thread C : k = 2
From Thread A : i = 3
From Thread A : i = 4
From Thread B : j = 1
From Thread B : j = 2
From Thread C : k = 3
From Thread C : k = 4
From Thread A : i = 5
Exit form A
From Thread B : j = 3
From Thread B : j = 4
From Thread C :k = 5
Exit from C
From Thread B : j = 5
Exit from B 84
THREAD MODEL: LIFE CYCLE OF THREAD
During the life time of a thread ,there are many states it
can enter, They are:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

A thread is always in one of these five states. It can


move from one state to another via a variety of ways.
85
STATE TRANSITION DIAGRAM OF A THREAD
OR
THREAD MODEL
Newborn

start stop

Active stop Killed


Running Runnable Dead
Threa yield thread
d

suspend Resume
sleep notify stop
wait

Idle thread Blocked


86
(Not Runnable)
NEWBORN STATE
 When we create a thread object ,the thread is born and is
said to be in newborn state.
 The thread is not still scheduled for running.
 At this time we can do only one of following with it:
 Scheduled it for running using start() method.
 Kill it using stop() method.
 If scheduled ,it moves to the runnable state

Newborn

Runnable Dead
state state
87

Fig. Scheduling a newborn thread


RUNNABLE STATE
 Runnable state means that the thread is ready for
execution and is waiting for the availability of the
processor.
 The threads has joined waiting queue for execution.
 If all threads have equal priority ,then they are given
time slots for execution in round robin fashion. i. e.
first-come ,first serve manner.

Runnable
Running
threads 88
threads
Relinquishing control using yield( ) method
RUNNABLE STATE
 Thread which is relinquishes( leaves) control,
joins the queue at the end and again waits for its
turn. this process of assigning time to thread is
known as time-slicing.
 If we want a thread to relinquish control to
another thread of equal priority before its turn
comes ,then yield() method is used

89
RUNNING STATE
 Running means that processor has given its time to
the thread for its execution. The thread runs until it
relinquishes control on its own or it is preempted by a
higher priority thread.
 A running thread may change its state to another
state in one of the following situations.

90
1) WHEN IT HAS BEEN SUSPENDED
USING SUSPEND() METHOD.
 A suspended thread can be reviewed by resume()
method.
 This is used when we want to suspend a thread for
some time due to certain reason ,but do not want to
kill it.
suspend

resume

Running Runnable suspended


Relinquishing control using suspend( ) method

91
2)IT HAS BEEN MADE TO SLEEP().
 We can put a thread to sleep for a specified time
period using the method sleep(time) where time is in
milliseconds.
 This means that the thread is out of the queue
during this time period .
 Thread is re-enters the runnable state as soon as this
time period is elapsed.

sleep(t)

after(t)

Running Runnable sleeping 92

Relinquishing control using sleep( ) method


3)WHEN IT HAS BEEN TOLD TO WAIT
UNTIL SOME EVENTS OCCURS.
 This done using the wait() method.
 The thread can be scheduled to run again using the
notify() method.

wait

notify

Running Runnable waiting

Relinquishing control using wait( ) method


93
BLOCKED STATE
 A thread is said to be blocked when it is prevented
from entering into the runnable state and
subsequently the running state.
 This happens when the thread is suspended ,sleeping
or waiting in order to satisfy certain requirements.
 A blocked thread is considered “not runnable” but not
dead and therefore fully qualified to run again.

94
DEAD STATE
 Every thread has a life cycle.
 A running thread ends its life when it has completed
executing its run() method.
 It is natural death. However we can kill it by sending
the stop. message to it as any state thus causing a
premature death for it.
 A thread can be killed as soon it is born or while it is
running or even when it is in “blocked" condition.

95
MAIN THREAD
 When a java program starts up, one thread begins
running immediately.
 It is the one that is executed when your program
begins, so it is usually called the main thread of your
program.
 Main thread is important for two reason:
 It is the thread from which other “child” threads will be
created.
 It must be the last thread to finish execution because it
performs various shutdown actions.
 Main thread is created automatically when your
program is started .it can be controlled through a
Thread object. 96
MAIN THREAD
 We can refer that object by calling the method
currentThread( ) which is public static member of
Thread.
Syntax : static Thread currentThread( ).
 This method returns reference to the thread in
which it is called. if we have reference to main
thread ,we can control it as any other thread.
 By default, the name main thread is main.
 Thread group is a data structure that controls the
state of a collection of threads as a whole. It is
managed by the particular run-time environment .
97
EXAMPLE: CONTROLLING THE MAIN THREAD
class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t =Thread.currentThread();
System.out.println(“Current thread :”+ t);
t. setName (“Mythread”);
System.out.println(“After name change :” + t);
try
{
for (int n=5; n>0 ;n--)
{
System.out.println(n);
Thread. sleep(1000);
98
} }
catch( InterruptedException e)
{
System.out.println(“Main thread interrupted “);
}
}
}
Output:
Current thread: Thread [main ,5,main]
After name change: Thread [My Thread ,5,main]
5
4
3
2
1 99
THREAD PRIORITIES
 Every thread in java has it’s own priority.
 Thread priority are used by thread scheduler to decide
when each thread should be allowed to run.
 In theory higher priority threads get more CPU time
than lower priority threads.
 When a lower priority thread is running higher
priority thread resumes (from sleeping or waiting for
on I/O) ,it will preempt the lower priority thread.
 Threads of equal priority should get equal access to the
CPU.for this ,thread that share the same priority
should yield control once in while.
 Every new thread that has created ,inherits the
priority of the thread that creates it.
 The priority is an integer value. 100
THREAD PRIORITIES
 Priority is in the range of Thread .
MIN_PRIORITY(0) and Thread .
MAX_PRIORITY( 10 ).
 To return thread to default priority ,specify
NORM_PRIORITY (5) .
 These priority are defined as final variables
within Thread.
 If the value is out of this range than the method
throws an exception IllegalArgumentException.
 Most user level processes should use
NORM_PRIORITY ,+1 OR -1
 Background tasks such as Network I/O and
screen repainting should use a value very near to
lower limit.
 We should be very careful when trying to use 101
very higher priority values.
THREAD PRIORITIES
 By assigning priorities to threads ,we can ensure
that they are given the attention they deserve.
 Whenever multiple threads are ready for execution
,the java system chooses the highest priority thread
and execute it . For a thread of lower priority to
gain control ,one of the following thing should be
happen:
1) It stops running at he end of run().
2) It is made to sleep using sleep().
3) It is told to wait using wait().
 If another higher priority thread comes along, the
currently running thread will be preempted by the
incoming thread and move it to the runnable state. 102
EXAMPLE:
class A extends Thread
{
public void run()
{
System.out.println(“threadA started”);
for ( int i=1; i<=4 ;i++)
{
System.out.println(“\t From thread A : i“+i);
}
System.out.println(“Exit from A”);
}
103
}
EXAMPLE
class B extends Thread
{
public void run()
{
System.out.println(“threadB started”);
for ( int j=1; j<=4 ;j++)
{
System.out.println(“\t From thread B :
j“+j);
}
System.out.println(“Exit from B”);
}
104
}
EXAMPLE
class C extends Thread
{
public void run()
{
System.out.println(“threadB started”);
for ( int k=1; k<=4 ;k++)
{
System.out.println(“\t From thread C: k“+k);
}
System.out.println(“Exit from C”);
}
105
}
EXAMPLE
class ThreadPriority
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t3.setPriority (Thread . MAX_PRIORITY);
t2.setPriority (t1.getPriority( ) + 1);
t1.setPriority ( Thread . MIN_PRIORITY);
106
EXAMPLE
System.out.println( “start thread A”);
t1.start();
System.out.println( “start thread B”);
t2.start();
System.out.println( “start thread C”);
t3.start();
System.out.println(“End of main thread “);
}}

107
OUTPUT
Start thread A
Start thread B
Start thread C
threadB started
from thread B: j=1
from thread B: j=2
threadC started
from thread C: j=1
from thread C: j=2
from thread C: j=3
from thread C: j=4
108
OUTPUT

Exit from C
End of main thread
from thread B: j=3
from thread B: j=4
Exit from B
threadA started
from thread A:i=1
from thread A: i=2
from thread A: i=3
from thread A: i=4
Exit from A 109
THREAD EXCEPTION
 The call to sleep() method should enclosed in a try
block and followed by a catch block. this is necessary
because the sleep() method throws an exception
,which should be caught.
 Java run system will throw
IllegalThreadStateException whenever we attempt
to invoke a method that a thread cannot handle in
the given state.
 e.g. a sleeping thread can not deal with the resume()
method because a sleeping thread can not receive
any instructions.
 Whenever we call a thread that may throw an
exception ,we have to supply appropriate exception
handler to catch it.
 Here ,the example of different Exception in
multithreading are given in next slide: 110
catch(ThreadDeath e)
{
………………
………………//Killed thread
}
catch( InterruptedException e)
{
………………//can not handle it in the current state
………………
}
catch(IllegalArgumentException e)
{
……………… //illegal method argument
………………
}
catch(Exception e) 111
{
………………}
SYNCHRONIZATION
 When two or more threads need to access to a shared
resource , they need some way to ensure that the
resource will be used by only one thread at a time. The
process of achieving this is called synchronization.
 For example ,one thread may try to read a record
from a file while another is still writing to the same
file. Depending on situation we may get strange result.
We can avoid this by synchronization.
 Monitor(semaphore) concept is key to
synchronization .
 Monitor is an object that is used as a mutually
exclusive lock or mutex.
112
SYNCHRONIZATION
 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. Monitor is like a key and the
thread that holds the key can only open the lock.
 All the other threads attempting to enter the
locked monitor will be suspended until the first
thread exists the monitor. This other threads are
said to be waiting for the monitor.
 We can synchronize code in two ways:

1) Using synchronized Methods

2) The synchronized statement 113


USING SYNCHRONIZED METHODS
 To create object’s monitor ,just call a method that uses
synchronized keyword.
 While we declare a method with synchronized.java
creates monitor and hands it over to the thread that
calls the method first time. While a thread is inside a
synchronized method, all other threads that try to call
it on the same instance have to wait.
synchronized void method-name( )
{
// code here is synchronized
}
 When ever thread has completed its work of using
synchronized method(or block or code) ,it will hand
over the monitor to the next thread that is ready to use
114

the same resource.


EXAMPLE
class Callme
{
synchronized void call(String msg)
{
System.out.print( " [ " + msg);
try
{
Thread. sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("thread is interrupted"); 115
}
EXAMPLE
System.out.println(" ] ");
}}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ,String s)
{
target=targ;
msg=s;
t=new Thread(this); 116

t.start(); }
EXAMPLE
//synchronize calls to call()
public void run()
{
target . call(msg);
}}
class Threadsynchro
{
public static void main(String args[])
{
Callme target =new Callme();
Caller ob1=new Caller(target,"hello");
Caller ob2=new Caller(target,"synchronized");
Caller ob3=new Caller(target,"world");
117
EXAMPLE
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
}
118
}
OUTPUT

[ Hello ] [world] [Synchronized]

// without synchronization block


[ Hello [world [synchronized ] ] ]

119
THE SYNCHRONIZED STATEMENT
 Creating synchronized methods within classes that
you create will not work in all cases.
 For example , if you want to synchronize access to
objects of a class that was not designed for
multithreading access means that class does not use
synchronized methods.
 In addition if this class was created by a third party
,and you don’t have access to the source code .thus you
can’t add synchronized to that class.
 To access an synchronized object of this class, We can
use synchronized block by putting calling method of a
class in that block.
120
THE SYNCHRONIZED STATEMENT

synchronized (lock-object)
{
// statements to be synchronized
}

 Here, lock-object is a reference to the object being


synchronized.
 A synchronized block ensures that a call to a
method that is a member of lock-object occurs
only after the current thread has successfully
entered lock-object’s monitor. 121
EXAMPLE
class Callme
{
void call(String msg)
{
System.out.print( " [ " + msg);
try
{
Thread. sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("thread is interrupted");
122

}
EXAMPLE
System.out.print(" ] ");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ,String s)
{
target=targ;
msg=s;
t=new Thread(this);
t.start(); 123
}
EXAMPLE
//synchronize calls to call()
public void run()
{
synchronized (target)
{
target.call(msg);
}}}
class Threadsynchro
{
public static void main(String args[])
{
Callme target =new Callme();
Caller ob1=new Caller(target,"hello");
Caller ob2=new Caller(target,"synchronized");
124
Caller ob3=new Caller(target,"world");
EXAMPLE
try
{ ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
} }

125
OUTPUT

[ Hello ] [world] [Synchronized]

// without synchronization block


[ Hello [world [synchronized ] ] ]

126
DEADLOCK
 When two or more threads are waiting to gain control of
a resources which are already hold by another waiting
threads , and no one can further proceed ,such situation
is known as deadlock.
E.g.
Thread A : synchronized method2()
{ synchronized method1()
{
……………..
}
}
Thread B : synchronized method1()
{ synchronized method2()
{ 127

……………..}}
INTER THREAD COMMUNICATION
 Polling is used to check some condition repeatedly .
Once the condition is true appropriate action is taken.
 In polling system, consumer would waste many CPU
cycles, while it waited for the producer to produce. Once
producer complete it waits for to complete consumer to
finish.
 To avoid polling, Java includes inter process
communication mechanism via the wait(),notify() and
notifyAll() methods.
 This method are implemented as final methods in
object. (in package java.lang.Object)
 All three methods can be called only from within a
synchronized context.
128
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().
Syntax:
final void wait () throws InterruptedException
2.notify() wakes up the first thread that called wait ()
on the same object.
Syntax:
final void notify()
3. notifyAll() wakes up all the threads that called
wait() on the same object. The highest priority
thread will run fast.
Syntax :
final void notifyAll()
129
SUSPENDING, RESUMING & STOPPING THREADS
1. Stopping a thread :stop()
syntax :
threadName.stop();
This causes the thread to move to dead state.A
thread will also move to the dead state automatically
when it reaches the end of its method.
 The stop( ) method may be used when the premature
death of a read is desired.
2. Resuming thread
syntax :
threadName.resume();
 This causes the thread to move to runnable state.A
thread will also move to the dead state automatically in
certain situation. 130
3. Suspending thread :sleep() ,wait() and
suspend()
This all causes the thread to move to Blocked state
 threadName.sleep(t);

this makes thread to sleep for t time (in


milisecond), after time elapsed thread will goes into
runnable state.
 threadName.wait();

this tells thread to wait for some event to


complete, to gain control notify() method is called of
that thread.
 threadName.suspend();

this suspends thread for some reason and then using


resume () method thread goes into runnable state. 131
THREAD CLASS METHODS
Thread encapsulates a thread of execution. Thread class
defines several methods that help manage threads.

Method Meaning
 getName() : Obtain a thread’s name.
Set a thread’s name.
 setName() :
Obtain a thread’s priority.
 getPriority() :
Set a thread’s priority
 setPriority() :
Determine if a thread is still running.
 isAlive() : Wait for a thread to terminate.
 join() : Entry point for the thread.
 run() : Suspend a thread for a period of time.
 sleep() : Start a thread by calling its run 132
 start() : method.
USING ALIVE() AND JOIN() METHODS
 In multi-threading ,one thread can know when another
thread has ended or not by using two methods isAlive()
and join() method. isAlive() :
 We can know state of any thread by this methods.

 This method is defined by Thread class .its general


form is :
final boolean isAlive( )
 It returns true if the thread upon which it is called is
still running, It returns false otherwise.
 This method is occasionally useful.

133
JOIN()
 The join method causes the current thread to
wait until the thread upon which the join( )
method is called terminates.
 It s name comes from the concept of calling
thread waiting until the specified thread joins it.
 Join() also allows to specify a maximum amount
of time that user want to wait for the specified
thread to terminate.
 This method is defined by Thread class .its
general form is :
final void join( ) throws
InterruptedException
 Where the join () method either suspends the
current thread for timeout milliseconds or until
the thread it calls on terminates.
 This method is commonly used. 134
EXAMPLE: ISALIVE () AND JOIN()
class display implements Runnable
{
public void run()
{
int i=0;
while(i<4)
System.out.println(“Hello” + i ++) ;
}}
class Alivejoin_Demo
{

135
EXAMPLE: ISALIVE () AND JOIN()

public static void main(String args[])


{
display d=new display();
Thread t1=new Thread(d);
Thread t2=new Thread(d);
Thread t3=new Thread(d);
t1.start();
t2.start();
t3.start();
try
{ 136
EXAMPLE: ISALIVE () AND JOIN()
System.out.println(“Thread t1 is alive :” +
t1.isAlive());
System.out.println(“Waiting for finishing thread t1”);
// causes main thread to wait until t1 terminate
t1.join();
System.out.println(“Thread t1 is alive : ” +
t1.isAlive());
}
catch(InterruptedException e )
{
System.out.println(“thread t1 is inturrpted “);
}}} 137
Output:
Thread t1 is Alive :true
Hello : 0
Hello : 0
Hello : 0
Waiting for finishing thread t1
Hello : 1
Hello : 1
Hello : 1
Hello : 2
Hello : 2
Hello : 2
Hello : 3
Hello : 3
Hello : 3
138
Thread t1 is Alive : false
Thank you

139

You might also like