23IT1301 - OOPs - Unit - 3
23IT1301 - OOPs - Unit - 3
23IT1301 - OOPs - Unit - 3
3.1: Thread
Definition: Thread
A thread is a lightweight sub-process that defines a separate path of execution. It is the smallest
unit of processing that can run concurrently with the other parts (other threads) of the same
process.
1
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
DIFFERENCE BETWEEN THREAD AND PROCESS:
MULTITHREADING
A program can be divided into a number of small processes. Each small process can be
addressed as a single thread.
Definition: Multithreading
Multithreading is a technique of executing more than one thread, performing different tasks,
simultaneously.
Multithreading enables programs to have more than one execution paths which executes
concurrently. Each such execution path is a thread. For example, one thread is writing
content on a file at the same time another thread is performing spelling check.
2
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
MULTITASKING
Definition: Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
maximize the utilization of CPU.
3
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
Different states, a thread (or applet/servlet) travels from its object creation to object
removal (garbage collection) is known as life cycle of thread. A thread goes through various
stages in its life cycle. At any time, a thread always exists in any one of the following state:
1. New State
2. Runnable State
3. Running State
4. Waiting/Timed Waiting/Blocked state
5. Terminated State/ dead state
1. New State:
A new thread begins its life cycle in the new state. It remains in this state until the program starts
the thread by calling start() method, which places the thread in the runnable state.
A new thread is also referred to as a born thread.
When the thread is in this state, only start() and stop() methods can be called. Calling any other
methods causes an IllegalThreadStateException.
Sample Code: Thread myThread=new Thread();
2. Runnable State:
After a newly born thread is started, the thread becomes runnable or running by calling the run()
method.
A thread in this state is considered to be executing its task.
Sample code: myThread.start();
The start() method creates the system resources necessary to run the thread, schedules the thread
to run and calls the thread’s run() method.
3. Running state:
Thread scheduler selects thread to go from runnable to running state. In running state Thread
starts executing by entering run() method.
4
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
Thread scheduler selects thread from the runnable pool on basis of priority, if priority of two
threads is same, threads are scheduled in unpredictable manner. Thread scheduler behaviour is
completely unpredictable.
When threads are in running state, yield() method can make thread to go in Runnable state.
Timed Waiting:
A runnable thread can enter the timed waiting state for a specified interval of time by calling the
sleep() method.
After the interval gets over, the thread in waiting state enters into the runnable state.
Sample Code:
try {
Thread.sleep(3*60*1000);// thread sleeps for 3 minutes
}
catch(InterruptedException ex) { }
Blocked State:
When a particular thread issues an I/O request, then operating system moves the thread to
blocked state until the I/O operations gets completed.
This can be achieved by calling suspend() method.
After the I/O completion, the thread is sent back to the runnable state.
5. Terminated State:
A runnable thread enters the terminated state when,
(i) It completes its task (when the run() method has finished)
public void run() { }
(ii) Terminates ( when the stop() is invoked) – myThread.stop();
A terminated thread cannot run again.
New : A thread begins its life cycle in the new state. It remains in this state until the start() method
is called on it.
Runnable : After invocation of start() method on new thread, the thread becomes runnable.
Running : A thread is in running state if the thread scheduler has selected it.
Waiting : A thread is in waiting state if it waits for another thread to perform a task. In this stage
the thread is still alive.
Terminated : A thread enter the terminated state when it complete its task.
The “main” thread is a thread that begins running immediately when a java program starts
up. The “main” thread is important for two reasons:
5
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
1. It is the thread form which other child threads will be spawned.
2. It must be the last thread to finish execution because it performs various shutdown actions.
Although the main thread is created automatically when our program is started, it can be
controlled through a Thread object.
To do so, we must obtain a reference to it by calling the method currentThread().
Example:
class CurrentThreadDemo {
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println(“Current Thread: “+t);
try {
for(int n=5;n>0;n--) {
System.out.println(n);
Thread.sleep(1000);// delay for 1 second
}
} catch(InterruptedException e) {
System.out.println(“Main Thread Interrrupted”);
}
}
}
Output:
Current Thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1
6
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
We can create threads by instantiating an object of type Thread. Java defines two ways to
create threads:
7
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
}
2. Override the run() method to define the code executed by the thread.
3. Create an object of type Thread by passing a Runnable object as argument.
Thread t=new Thread(Runnable threadobj, String threadName);
4. Invoke the start() method on the instance of the Thread class.
t.start();
Example:
class MyThread implements Runnable
{
Output:
Thread-0 # Printing 0
Thread-1 # Printing 0
8
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
Thread-1 # Printing 1
Thread-0 # Printing 1
Thread-1 # Printing 2
Thread-0 # Printing 2
9
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
1. Create a class that extends java.lang.Thread class.
public class MyThread extends Thread
{
---
}
2. Override the run() method in the sub class to define the code executed by the thread.
3. Create an object of this sub class.
MyThread t=new MyThread(String threadName);
4. Invoke the start() method on the instance of the subclass to make the thread for
running.
start();
Example:
10
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
Thread-1 # Printing 0
Thread-1 # Printing 1
Thread-0 # Printing 1
Thread-0 # Printing 2
Thread-1 # Printing 2
Thread priority determines how a thread should be treated with respect to others.
Every thread in java has some priority, it may be default priority generated by JVM or
customized priority provided by programmer.
Example:
11
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+
Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Threads should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts
may arise when parallel-running threads attempt to modify a common variable at the same time.
Why use Synchronization
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
12
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This
can be done by two ways in java:
1. by synchronized method
2. by synchronized block
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); }
}
13
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
}
}
14
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
2. Synchronized block in java
Synchronized block can be used to perform synchronization on any specific resource of
the method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
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
}
15
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
It is implemented by following methods of Object class and all these methods can be called only
from within a synchronized context.
S.No. Method & Description
1 public final void wait() throws InterruptedException
Causes the current thread to wait until another thread invokes the notify().
2 public final void wait(long timeout) throws InterruptedException
Causes current thread to wait until either another thread invokes the notify() method or the
notifyAll() method for this object, or a specified amount of time has elapsed.
Parameters:
timeout − the maximum time to wait in milliseconds.
3 public final void notify()
Wakes up a single thread that is waiting on this object's monitor.
4 Public final void notifyAll()
Wakes up all the threads that called wait( ) on the same object.
Difference between wait() and sleep()
17
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
Example: The following program illustrates simple bank transaction operations with inter-
thread communication:
class Customer{
int Balance=10000;
if(Balance<amount)
{
System.out.println("Less balance; Balance = Rs. "+Balance+"\nWaiting for deposit...\n");
try
{
wait();
}
catch(Exception e){}
}
Balance-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit... Rs. "+amount);
Balance+=amount;
System.out.println("deposit completed... Balance = "+Balance);
notify();
}
}
class ThreadCommn
{
public static void main(String args[]) {
Customer c=new Customer();
new Thread()
{
public void run(){c.withdraw(20000);}
}.start();
new Thread(){
public void run(){c.deposit(15000);}
18
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
}.start();
}
}
Output:
going to withdraw...20000
Less balance; Balance = Rs. 10000
Waiting for deposit...
User Threads are threads which are created by the application or user. They are high-priority
threads. The JVM will wait for any user thread to complete its task before terminating it.
On the other hand, Daemon Threads are threads which are mostly created by the JVM. These
threads are low-priority threads whose only role is to provide services to user threads.
Properties:
A user thread can be changed to Daemon thread by using setDaemon() method of thread
class.
public boolean isDaemon(): This method is used for checking the status of a thread. It
returns true if the thread is Daemon else it returns false.
19
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
setDaemon() method can only be called before starting the thread. This method would
throw IllegalThreadStateException if you call this method after Thread.start() method.
Methods:
The java.lang.Thread class provides two methods for java daemon thread.
1) public void setDaemon(boolean is used to mark the current thread as daemon thread or
status) user thread.
2) public boolean isDaemon() is used to check that current thread is daemon or not.
Example:
if(Thread.currentThread().isDaemon()){
System.out.println("Daemon thread executing");
}
else{
System.out.println("user(normal) thread executing");
}
}
public static void main(String[] args){
DaemonThreadExample1 t1=new DaemonThreadExample1();
DaemonThreadExample1 t2=new DaemonThreadExample1();
t1.setDaemon(true);
t1.start();
t2.start();
}
}
Output:
20
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
Thread group in java is used to group similar threads into one unit. A thread group can
also contain other thread groups.
Thread groups are constructed using java.lang.ThreadGroup class.
The main use of thread groups is that you can handle multiple threads simultaneously.
In such way, we can suspend, resume or interrupt group of threads by a single method
call.
3) void destroy() destroys this thread group and all its sub groups.
21
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
While creating the threads itself, specify it’s group using constructor which takes ThreadGroup
and name of a thread as arguments
}
}
22
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
Output:
3.8: Exceptions
Definition:
Exceptions are events that occur during the execution of programs that interrupt the normal flow
of a program (e.g. divide by zero, array access out of bound, etc.).
1. In Java, an exception is an object that wraps an error event that occurred within a method
and contains:
o Information about the error including its type
o The state of the program when the error occurred
o Optionally, other custom information
2. Occurrence of any kind of exception in java applications may result in an abrupt
termination of the JVM or simply the JVM crashes.
23
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
All exceptions and errors extend from a common java.lang.Throwable parent class.
Exceptions: Exceptions represents errors in the Java application program, written by the user.
Because the error is in the program, exceptions are expected to be handled, either
Try to recover it if possible
Minimally, enact a safe and informative shutdown.
Sometimes it also happens that the exception could not be caught and the program may get
terminated. Eg. ArithmeticException
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run
out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Errors: Errors represent internal errors of the Java run-time system which could not be handled
easily. Eg. OutOfMemoryError.
24
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
DIFFERENCE BETWEEN EXCEPTION AND ERROR:
25
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
Types of Exceptions:
1. Checked Exceptions
2. Unchecked Exceptions
1. Checked Exceptions:
The classes that extend Throwable class except RuntimeException and Error are known
as checked exceptions
It is an exception that is typically a user error or a problem that cannot foreseen by the
programmer.
Checked exceptions are checked at compile-time.
Checked Exceptions forces programmers to deal with the exception that may be thrown.
Checked exceptions must be caught using try.. catch () block or we should throw the
exception using throws clause. If you dont, compilation of program will fail.
Example:
1. ClassNotFoundException 5. NoSuchFileException
2. CloneNotSupportedException 6. NoSuchMethodException
3. IllegalAccessException, 7. IOException
4. MalformedURLException.
Output:
To make program able to compile, you must handle this error situation in try-catch block.
Below given code will compile absolutely fine.
26
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
With try-catch
import java.io.*;
import java.io.*;
Output:
2. Unchecked Exceptions(RunTimeException):
27
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
28
class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
Output:
Exception Handling
try Block:
The java code that might throw an exception is enclosed in try block. It must be used
within the method and must be followed by either catch or finally block.
If an exception is generated within the try block, the remaining statements in the try
block are not executed.
catch Block:
Exceptions thrown during execution of the try block can be caught and handled in a
catch block.
On exit from a catch block, normal execution continues and the finally block is
executed.
finally Block:
A finally block is always executed, regardless of the cause of exit from the try block, or
whether any catch block was executed.
Generally finally block is used for freeing resources, cleaning up, closing connections
etc.
Even though there is any exception in the try block, the statements assured by finally
block are sure to execute.
Rule:
For each try block there can be zero or more catch blocks, but only one finally
block.
The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort).
The try-catch-finally structure(Syntax):
try {
// Code block
}
catch (ExceptionType1 e1) {
// Handle ExceptionType1 exceptions
}
catch (ExceptionType2 e2) {
// Handle ExceptionType2 exceptions
}
// ...
finally {
// Code always executed after the
// try and any catch block
}
class Simple
{
public static void main(String args[])
{
int data=50/0;
Output:
Program Explanation:
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
Example:
public class Demo
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
}
}
Output: java.lang.ArithmeticException: / by zero
finally block is always executed
rest of the code...
Definition: try block within a try block is known as nested try block.
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
System.out.println("...End of Program...");
}
}
Output:
Quotient = 2
array index out of bound exception
...End of Program...
Rules:
At a time only one Exception can occur and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception.
Syntax:
try {
// Code block
}
Example:
try
{
int a[]= {1,5,10,15,16};
System.out.println("a[1] = "+a[1]);
System.out.println("a[2]/a[3] = "+a[2]/a[3]);
System.out.println("a[5] = "+a[5]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
Output:
a[1] = 5
a[2]/a[3] = 0
ArrayIndexOutOfBounds Exception occurs
rest of the code
Before catching an exception, it is must to throw an exception first. This means that
there should be a code somewhere in the program that could catch exception thrown in the
try block.
The Exception reference must be of type Throwable class or one of its subclasses. A detail
message can be passed to the constructor when the exception object is created.
Example:
Output:
In this example, we have created the validate method that takes integer value as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a
message welcome to vote.
Example:
1. import java.util.Scanner;
2. public class ThrowsDemo
3. {
4. static void divide(int num, int din) throws ArithmeticException
5. {
6. int result=num/din;
7. System.out.println("Result : "+result);
8. }
Output:
Enter the Numerator :
4
Enter the Denominator :
0
Can't Handle : divide by zero ERROR
** Continue with rest of the code **
Enter the Numerator :
6
Enter the Denominator :
2
Result : 3
** Continue with rest of the code **
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions
are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.
S. No. Exception Description
Thrown when a problem in arithmetic
1. ArithmeticException
operation is noticed by the JVM.
Thrown when you access an array with an
2. ArrayIndexOutOfBoundsException
illegal index.
Thrown when you try to access a class
3. ClassNotFoundException
which is not defined
Thrown when you try to access a non-
4. FileNotFoundException
existing file.
Thrown when the input-output operation
5. IOException
has failed or interrupted.
Thrown when a thread is interrupted when
6. InterruptedException
it is processing, waiting or sleeping
7. IllegalAccessException Thrown when access to a class is denied
Thrown when you try to access any field or
8. NoSuchFieldException
variable in a class that does not exist
Thrown when you try to access a non-
9. NoSuchMethodException
existing method.
10. NullPointerException Thrown when you refer the members of a
null object
Thrown when a method is unable to
11. NumberFormatException
convert a string into a numeric format
Thrown when you access a String array
12. StringIndexOutOfBoundsException
with an illegal index.
Output:
NullPointerException..
Output:
Exception types created by the user to describe the exceptions related to their applications are
known as User-defined Exceptions or Custom Exceptions.
The following program illustrates how user-defined exceptions can be created and thrown.
}
else
{
EvenNoException exp=new EvenNoException(arr[i]+" is
not an Even Number");
throw exp;
}
}
catch(EvenNoException exp)
{
System.out.println("Exception thrown is "+exp);
}
} // for loop
} // main()
} // class
Output:
2 is an Even Number
Exception thrown is EvenNoException: 3 is not an Even Number
4 is an Even Number
Exception thrown is EvenNoException: 5 is not an Even Number
Program Explanation:
In the above program, the EvenNumberException class is created which inherits the Exception
super class. Then the constructor is defined with the call to the super class constructor. Next, an
array arr is created with four integer values. In the main(), the array elements are checked one
by one for even number. If the number is odd, then the object of EvenNumberException class is
created and thrown using throw clause. The EvenNumberException is handled in the catch
block.
Basis for
final finally finalize
comparison
Basis for
final finally finalize
comparison
A Stack Trace is a list of method calls from the point when the application was started
to the current location of execution within the program. A Stack Trace is produced
automatically by the Java Virtual Machine when an exception is thrown to indicate the
location and progression of the program up to the point of the exception. They are
displayed whenever a Java program terminates with an uncaught exception.
We can access the text description of a stack trace by calling the printStackTrace()
method of the Throwable class.
The java.lang.StackTraceElement is a class where each element represents a single
stack frame.
We can call the getStackTrace() method to get an array of StackTraceElement
objects that we want analyse in our program.
Class Declaration
Following is the declaration for java.lang.StackTraceElement class
public final class StackTraceElement extends Object implements Serializable
Class constructors
Constructor & Description
StackTraceElement(String declaringClass, String methodName, String fileName, int
lineNumber)
This creates a stack trace element representing the specified execution point.
Parameters:
declaringClass – the fully qualified name of the class containing the execution point
represented by the stack trace element.
methodName – the name of the method containing the execution point represented by
the stack trace element.
fileName – the name of the file containing the execution point represented by the stack
trace element, or null if this information is unavailable
lineNumber – the line number of the source line containing the execution point
represented by this stack trace element, or a negative number if this
information is unavailable. A value of -2 indicates that the method
containing the execution point is a native method.
Throws: NullPointerException – if declaringClass or methodName is null.
Example:
The following program for finding factorial(using recursion) prints the stack trace of a
recursive factorial function.
import java.util.Scanner;
System.out.println("return "+r);
return r;
}
Output:
Enter n: 3
Factorial (3):
StackTraceTest.factorial(StackTraceTest.java:10)
StackTraceTest.main(StackTraceTest.java:30)
Factorial (2):
StackTraceTest.factorial(StackTraceTest.java:10)
StackTraceTest.factorial(StackTraceTest.java:20)
StackTraceTest.main(StackTraceTest.java:30)
Factorial (1):
StackTraceTest.factorial(StackTraceTest.java:10)
StackTraceTest.factorial(StackTraceTest.java:20)
StackTraceTest.factorial(StackTraceTest.java:20)
StackTraceTest.main(StackTraceTest.java:30)
return 1
return 2
return 6