You are on page 1of 88

OBJECT ORIENTED PROGRAMMING THROUGH JAVA

By.
G.Praveen Kumar
Assit.Prof , IT Dept.
SNIST.

G.Praveen ITDept-SNIST 1
UNIT III

1.Exception handling -exception definition


2. benefits of exception handling,
3.exception hierarchy
4.usage of try, catch, throw, throws and finally
5. built in exceptions
6. creating own exception sub classes
7.Multi-Threading:-Thread definition
8.types of multitasking, uses of multitasking
9.thread life cycle
10.creating threads using Thread class and Runnable interface
11.synchronizing threads
12. daemon thread.
13.Applications of multithreading

G.Praveen ITDept-SNIST 2
Objective:- On the completion of the unit, a student should be able to:

i) Understand benefits of exception handling


ii) Handle built-in and user defined exceptions
iii) Understand the uses of multi-threading
iv) Create multi-threaded programs using either Thread class or
Runnable interface
v) Know how to synchronize threads
 

G.Praveen ITDept-SNIST 3
Program Errors

There are basically 3 types of errors in a java program:


1.Compile-time errors
2.Run-time errors
3.Logical errors.

G.Praveen ITDept-SNIST 4
1.Compile-time errors:
•These are syntactical errors found in
the code, due to which a program
fails to compile.

•For example, forgetting a semicolon


at the end of the a java program, or
writing a statement without proper
syntax will result in compilation-
time error.
G.Praveen ITDept-SNIST 5
Class Cerror
{
public static void main(String args[])
{
System.out.println(“Compilation Error…..”)
}
}
D:\>javac Cerror.java
CError.java:4: ';' expected
}
^
1 error
G.Praveen ITDept-SNIST 6
2.Run-time Errors: These are the
errors which represent inefficiency of
the computer system to execute a
particular statement, means computer
system can not process.
For example,
division by zero error occur at run-
time.

G.Praveen ITDept-SNIST 7
class RError{
public static void main(String args[])
{
int a=10,b=0;
System.out.println(“a/b: ”+(a/b));
}}

D:\>javac RError.java

D:\>java RError
Exception in thread "main" java.lang.ArithmeticException: / by zero
at RError.main(RError.java:4)

G.Praveen ITDept-SNIST 8
3.Logical errors:
•These errors depict flaws in the
logic of the program.
•The programmer might be using a
wrong formula or the design of the
program itself is wrong.
•Logical errors are not detected
either by the java compiler or JVM.

Cont…
G.Praveen ITDept-SNIST 9
•Logical errors means the logic of
the program is wrong and these are
identified after observing the
output.

•The programmer is solely


responsible for them

G.Praveen ITDept-SNIST 10
class LError{
int sum(int a,int b){
return a-b;
}
public static void main(String args[]){
LError le=new LError();
System.out.println("Sum is: "+le.sum(20,10));
}
}
D:\>javac LError.java
D:\>java LError
Sum is: 10
G.Praveen ITDept-SNIST 11
What is an Exception?
• Dictionary Meaning: Exception is an
abnormal condition.”
• According to java language exception
is an event that disrupts the normal
flow of the program. It is an object
which is thrown at runtime
• An other words, an exception is a run-
time error.
G.Praveen ITDept-SNIST
Cont…
12
•Because of Exceptions the flow of
program execution is getting disturbed so
that program execution may continue (or)
may not be continued.
•Examples
• Division by zero
• Attempts to use an array index
out of bounds.
• Number input in wrong format
• Unable to write
G.Praveen ITDept-SNIST 13
Exception Handling
• Whenever an exception is occurred, handling
those exceptions called as “Exception
Handling”.
• Performing action in response to exception
• Examples
Exit program (abort)Ignore exception
Deal with exception and continue
• Print error message
• Request new data
• Retry actionG.Praveen ITDept-SNIST 14
Error:- Error is irrecoverable
e.g. OutOfMemoryError, VirtualMachineError, AssertionError
etc.
Difference between error and exception
Errors indicate serious problems and abnormal conditions that
most applications should not try to handle.
Error defines problems that are not expected to be caught
under normal circumstances by our program.
For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code.
A developer can handle such conditions and take necessary
corrective actions.
Few examples –
DivideByZero exception
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
G.Praveen ITDept-SNIST 15
Benefits of Exception Handling
a. It allows us to fix the error.
b. It prevents program from automatically
terminating.
c. Separates Error-Handling Code from
Regular Code..
d. Conventional programming combines
error detection, reporting, handling
code with the regular code, leads to
confusion. G.Praveen ITDept-SNIST 16
Exception-Handling Fundamentals

 A Java exception is an object that


describes an exceptional condition
that has occurred in a piece of code.

 When an exceptional condition


arises, an object representing that
exception is created and thrown in
the method that caused the error.
G.Praveen ITDept-SNIST 17
 An exception can be caught to handle
it or pass it on.

 Exceptions can be generated by the


Java run-time system, or they can be
manually generated by your code.

 Java exception handling is managed


by via five keywords: try, catch,
throw, throws, and finally.
G.Praveen ITDept-SNIST 18
Cont….
 Program statements to monitor are
contained within a try block.
 If an exception occurs within the try
block, it is thrown.
 Code within catch block catch the
exception and handle it.
 System generated exceptions are
automatically thrown by the Java run-
time system.
G.Praveen ITDept-SNIST 19
To manually throw an exception, use
the keyword throw
Any exception that is thrown out of a
method must be specified as such by a
throws clause.
Statements contained in the finally
block will be executed, regardless of
whether or not an exception is raised.

G.Praveen ITDept-SNIST 20
An exception is an error which can be
handled. It means an exception happens,
the programmer can do something to
avoid any harm.

But an error is an error which cannot


be handled, it happens and the
programmer cannot do anything
G.Praveen ITDept-SNIST 21
Types of exceptions:- There are two types of exceptions
1)Checked exceptions
2)Unchecked exceptions
Checked exceptions:- The Checked Exceptions witch are checked by
the compiler for smooth execution of program are called checked
exception
Examples of Checked Exceptions :-
ClassNotFoundException ,
MOBILE FORGOT,
NoSuchFieldException,
EOFException etc.
NOTE:- In our program if any choice of raising checked exception
then compulsory we should handle that checked exception (by using
try-catch or throws keyword ) Other wise we will get Compile
Time exception

G.Praveen ITDept-SNIST 22
Unchecked Exceptions:- The exception which are
not checked by compiler and programmer handled or
not such type of exception are called unchecked
exception and programmer provide a safe execution of
the program and exit from the program.

Examples of Unchecked Exceptions:-


ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
NegativeArraySizeException etc.

G.Praveen ITDept-SNIST 23
Java Exception Class Hierarchy

G.Praveen ITDept-SNIST 24
Java Exception Class Hierarchy
Exception

Built Exceptions User Defined Exceptions

Un Checked Exceptions Checked Exceptions

G.Praveen ITDept-SNIST 25
Java Exception Handling Keywords:-
There are 5 keywords used in java exception handling.

1.try
2.catch
3.finally
4.throw
5.throws

G.Praveen ITDept-SNIST 26
Try Block:-The try block contains a block of program
statements with in which an exception might occur(risky
code) . A try block is always followed by a catch block,
which handles the exception that occurs in associated try
block. A try block must followed by a Catch block or
Finally block or both.
Syntax of try block
Try
{
//statements that may cause an exception
}

G.Praveen ITDept-SNIST 27
Catch Block:- catch block must be associated with a
try block. The corresponding catch block executes if
an exception of a particular type occurs within the try
block. For example if an arithmetic exception occurs in
try block then the statements enclosed in catch block
for arithmetic exception executes.
Syntax of try catch in java
Try
{ //statements that may cause an exception }
catch (exception(type) e(object))
{
//error handling code
}
G.Praveen ITDept-SNIST 28
public class Pro1{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code1...");
}
}

OUTPUT:-
C:\praveen\UNTI-4>java Pro1
java.lang.ArithmeticException: / by zero
rest of the code1...

G.Praveen ITDept-SNIST 29
Internal working of java try-catch block

G.Praveen ITDept-SNIST 30
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:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the
exception occurred).
Causes the program to terminate.
But if exception is handled by the application
programmer, normal flow of the application is
maintained i.e. rest of the code is executed.

G.Praveen ITDept-SNIST 31
Multiple Catch Blocks:-If user have to perform different tasks in a single
code at the occurrence of different Exceptions these exception s are handled
by use java multi catch block.
A try block can be followed by multiple catch blocks. After one catch
statement executes, the others are bypassed, and execution continues
after the try/catch block.
The syntax for multiple catch blocks looks like the following 
Syntax:-
try {
// Protected code
}
catch(ExceptionType1 e1)
{
// Catch block
}catch(ExceptionType2 e2)
{
// Catch block }catch(ExceptionType3 e3)
{
// Catch block G.Praveen ITDept-SNIST 32
From The above syntax three catch blocks, you can have any
number of them after a single try. If an exception occurs in the
protected code, the exception is thrown to the first catch block in
the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes
down to the second catch statement. This continues until the
exception either is caught or falls through all catches, in which
case the current method stops execution and the exception is
thrown down to the previous method on the call stack.

G.Praveen ITDept-SNIST 33
class MCatch {
public static void main(String args[]) { OUTPUT:-
1) C:\praveen\UNIT-4>java MCatch
try {
a=0
int a = args.length; Divide by 0: java.lang.ArithmeticExceptio
System.out.println("a = " + a); zero
int b = 42 / a; After try/catch blocks.
int c[] = { 1 }; EXCEPTION FREE ZONE
c[42] = 99; 2) C:\praveen\UNIT-4>java MCatch 10
} a=1
catch(ArithmeticException e) Array index oob:
{ java.lang.ArrayIndexOutOfBoundsExcep
After try/catch blocks.
System.out.println("Divide by 0: " + e);
EXCEPTION FREE ZONE
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
System.out.println("EXCEPTION FREE ZONE ");
}}
G.Praveen ITDept-SNIST 34
class MCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(Exception e){System.out.println("common task completed");}
/*catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}*/
System.out.println("After try/catch blocks.");
System.out.println("EXCEPTION FREE ZONE ");
}}
C:\praveen\UNIT-4>java M
a=0
common task completed
After try/catch blocks.
EXCEPTION FREE ZONE
G.Praveen ITDept-SNIST 35
Java Nested try block:-The try block within a try block is known
as nested try block in java
Each time a try statement is entered, the context of that exception is
pushed on the stack.
If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match.
This continues until one of the catch statements succeeds, or until
all of the nested try statements are exhausted.
If no catch statement matches, then the Java run-time system will
handle the exception.
NOTE:-Why use nested try block
Sometimes a situation may arise where a part of a block may cause
one error and the entire block itself may cause another error. In
such cases, exception handlers have to be nested.

G.Praveen ITDept-SNIST 36
try {
statement 1;
statement 2; //try-catch block inside another try block
try
{
statement 3;
statement 4; //try-catch block inside nested try block
try
{
statement 5;
statement 6;
} catch(Exception e2){
//Exception Message
}
} catch(Exception e1) {
//Exception Message
} } //Catch of Main(parent) try block
catch(Exception e3) {
//Exception Message
}
G.Praveen ITDept-SNIST 37
try  
{  
    statement 1;  
    statement 2;  
    try  
    {  
        statement 1;  
        statement 2;  
    }  
    catch(Exception e)  
    {  
    }  
}  
catch(Exception e)  
{  
}  

G.Praveen ITDept-SNIST 38
class NTry {
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
if(a==1) a = a/(a-a);
if(a==2)
{
int c[] = { 1 };
c[42] = 99;
}}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}}}

G.Praveen ITDept-SNIST 39
OUTPUT:-
C:\praveen\UNIT-4>java NTry
Divide by 0: java.lang.ArithmeticException: / by zero

C:\praveen\UNIT-4>java NTry 1
a=1
Divide by 0: java.lang.ArithmeticException: / by zero

C:\praveen\UNIT-4>java NTry 2
a=1
Divide by 0: java.lang.ArithmeticException: / by zero

C:\praveen\UNIT-4>java NTry 23
a=1
Divide by 0: java.lang.ArithmeticException: / by zero

C:\praveen\UNIT-4>

G.Praveen ITDept-SNIST 40
finally block:-finally block is a block that is used to execute
significant code such as closing connection, stream etc.

Java finally block follows try or catch block..

G.Praveen ITDept-SNIST 41
Finally block is use to put "cleanup" code such as closing a file, closing
connection etc.

1. finally example where exception doesn't occur.


class Finally1{
public static void main(String args[]){
try{
int data=25/5; C:\praveen\UNIT-4>java Finally1
System.out.println(data); 5
} finally block is always executed
catch(NullPointerException e){ rest of the code...
System.out.println (e);
}
finally{System.out.println("finally block is always

executed");}
System.out.println("rest of the code...");
}
}
G.Praveen ITDept-SNIST 42
2. finally example where exception occurs and handled.
public class Finally2{  
  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");}  
  System.out.println("rest of the code...");  
  }  
}  

G.Praveen ITDept-SNIST 43
class ThrowDemo { // Demonstrate throw.
static void demoproc()
{
try {
int data=50/10;
throw new NullPointerException(); OUTPUT:-
} C:\praveen\UNIT-4>java ThrowDemo
Caught inside demoproc.
catch(ArithmeticException e) Recaught: java.lang.NullPointerException
{
System.out.println(e);
}
catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}}
public static void main(String args[]) {
try {
demoproc();
}catch(NullPointerException e) {
System.out.println("Recaught: G.Praveen
" + e); ITDept-SNIST 44
throw keyword:-The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or unchecked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception(user-defined exception).
 Program can also throw an exception explicitly, using the throw statement.
The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
There are two ways you can obtain a Throwable object:
using a parameter into a catch clause, or
creating one with the new operator.
The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed.
It finds the catch which is suitable, if it does find a match, control is transferred
to that statement.
If not, then the next enclosing try statement is inspected, and so on.

If no matching catch is found, then the default exception handler halts the
program and prints the stack trace.
  

G.Praveen ITDept-SNIST 45
throws keyword:-throws is a keyword in java language which is used to throw
the exception which is raised in the called method to it's calling method throws
keyword always followed by method signature.

G.Praveen ITDept-SNIST 46
Difference between throw and throws in Java:- There are many differences
between throw and throws keywords

throw throws
Java throw keyword is used to Java throws keyword is used to declare
explicitly throw an exception. an exception.
Checked exception cannot be Checked exception can be propagated
propagated using throw only. with throws.
Throw is followed by an instance. Throws is followed by class.
Eg:-void m(){   void m()throws ArithmeticException{  
throw new ArithmeticException("sorry"); throw new ArithmeticException("sorry");
    }  
}  
Throw is used within the method. Throws is used with the method
signature.
We cannot throw multiple exceptions. We can declare multiple exceptions
e.g.
public void method()throws
G.Praveen ITDept-SNIST 47
IOException,SQLException.
Java’s Built-in Exceptions:-
Inside java.lang package, Java defines several exception classes.

These exceptions are subclasses of the standard type RuntimeException.

Since java.lang is implicitly imported into all Java programs, most


exceptions derived from RuntimeException are automatically available.

Furthermore, they need not be included in any method’s throws list.

These are called unchecked exceptions because the compiler does not
check to see if a method handles or throws these exceptions.

Exceptions defined by java.lang those must be included in a method’s


throws list if that method can generate one of these exceptions and does not
handle it itself. These are called checked exceptions.

G.Praveen ITDept-SNIST 48
Java’s Unchecked RuntimeException Subclasses

G.Praveen ITDept-SNIST 49
G.Praveen ITDept-SNIST 50
Java’s Checked Exceptions Defined in java.lang

G.Praveen ITDept-SNIST 51
Creating Your Own Exception Subclasses
To create own exception types to handle situations specific to your applications.

To do this, define a subclass of Exception (which is, of course, a subclass


of Throwable).

The Exception class does not define any methods of its own. It does, of
course, inherit those methods provided by Throwable.

Thus, all exceptions, including those that you create, have the methods
defined by Throwable available to them.

You may also wish to override one or more of these methods in exception
classes that you create.

G.Praveen ITDept-SNIST 52
Every user defined Exception last word must be Exception since every
exception is a class.
E.g., AgeException
MarksOutOfBoundsException

Whenever a superclass is Exception then that type of User defined


Exception is Checked Exception.
E.g., class XYZException extends Exception{
// body of the class
}
If the superclass is RuntimeException then that user defined Exception
is unchecked Exception.
E.g., class XYZException extends RunTimeException{
//body of the class
}

G.Praveen ITDept-SNIST 53
class MyException extends Exception { // This program creates a custom exception type.
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20); Called compute(1)
}
Normal exit
catch (MyException e) {
System.out.println("Caught " + e); Called compute(20)
} Caught MyException[20]
}
}
G.Praveen ITDept-SNIST 54
Custom Exception in Java:-If any exception is design by the user known as user
defined or Custom Exception. Custom Exception is created by user.

Rules to design user defined Exception


1.Create a package with valid user defined name.
2.Create any user defined class.
3.Make that user defined class as derived class of Exception or RuntimeException
class.
4.Declare parametrized constructor with string variable.
5.call super class constructor by passing string variable within the derived class
constructor.
6.Save the program with public class name.java

G.Praveen ITDept-SNIST 55
Single Tasking :- A task means doing some calculation, processing, etc.

Generally, a task involves execution of a group of statements, for example executing a


program.

In single tasking environment, only one task is given to processor at a time.

This means we are wasting a lot of processor time and processor has to sit idle without
any job for a long time.

This is the drawback in single tasking

G.Praveen ITDept-SNIST 56
Multi Tasking :-multi tasking environment perform several tasks are given
to processor at a time.

Multi tasking can be done by scheduling algorithms.

most of the processor time is getting engaged and it is not sitting idle.

Uses:
To use the processor time in a better way.
To achieve good performance.
To make processor not to sit idle for long time.

G.Praveen ITDept-SNIST 57
Multitasking:- Multitasking is a process of executing multiple tasks
simultaneously. We use multitasking to utilize the CPU. Multitasking can
be achieved by two ways:
1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)

1)Process-based Multitasking (Multiprocessing):-


 Each process have its own address in memory i.e. each
process allocates separate memory area.
 Process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another require some time for
saving and loading registers, memory maps, updating lists etc.
Eg:- 1) Action to listen the class
2) charting with friends
3) playing with mobile
4) action to write a notes
5) looking to outside
G.Praveen ITDept-SNIST 58
2) Thread-based Multitasking (Multithreading):-
Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread is low.
Eg:-

G.Praveen ITDept-SNIST 59
Process-based vs. Thread-based
1. A process is a program that is 1. A thread is a separate path of
executing. execution.

2. Processes are heavy weight 2. Threads are light weight


tasks that require their own process. They share the same
separate address spaces. address space and cooperatively
share the same heavy weight
process.
3. Interprocess communication is
expensive and limited. 3. Inter thread communication is
inexpensive.
4. Context switching from one
process to another is also costly. 4. Context switching from one
thread to the next is low cost.

G.Praveen ITDept-SNIST 60
Thread Life cycle (Thread States):- The life cycle of the thread in java is controlled
by JVM. Starting from the birth of a thread, till its death, a thread exists in different
states which are collectively called “Thread Life Cycle”.
T

)
ar t( Schedular dispatch
st

MAIN MEMORY
G.Praveen ITDept-SNIST 61
1. New State:-If any new thread class is created that represent new state of
a thread, In new state thread is created and about to enter into main
memory.
No memory is available if the thread is in new state.

2. Ready (Runnable) State: A thread start its life from Runnable state. A
thread first enters Runnable state after the invoking of start() method but a
thread can return to this state after either running, waiting, sleeping or
coming back from blocked state also. On this state a thread is waiting
for a turn on the processor.

3. Running State: Whenever the thread is under execution known as


running state. There are several ways to enter in Runnable state but there
is only one way to enter in Running state: the scheduler select a thread
from Runnable pool.

G.Praveen ITDept-SNIST 62
4. Blocked State: A thread can enter in this state because of waiting the
resources that are hold by another thread.

5. Dead State: A thread can be considered dead when its run() method
completes. If any thread comes on this state that means it cannot ever run
again. no memory is available for the thread if its comes to dead state.

G.Praveen ITDept-SNIST 63
Thread Life Cycle (Contd..)
A thread will be born when it is created using Thread class as:
Thread obj=new Thread();
A thread goes into runnable state when start() method is applied on it.

That is void start() method is used to call the public void run() method.

From runnable state, a thread may get into not-runnable state, when sleep()
or wait() or suspend() methods act on it.

notify() and resume() methods are used to restart waiting and suspended
threads respectively.
yield() method causes the currently executing thread object to temporarily
pause and allow other threads to execute.

Thread Death class will be invoked whenever the stop() method is called.

G.Praveen ITDept-SNIST 64
Single Thread System Vs. Multi Thread System

• Single-thread System use an • The advantage of multi threading is


approach called an event loop that the main loop, pooling
with pooling. mechanism is eliminated.

• A Single thread of control runs • Multithreading enables us to write


in an infinite loop, pooling a very efficient programs that make
single event queue to decide maximum use of CPU. Because
what to do next. ideal time can be kept to a
minimum.
• In a single-threaded
environment, when a thread • One thread can pause with out
blocks because it is waiting for stopping other parts of the
some resources the entire program. Java supports multi
program stops running. threading.

G.Praveen ITDept-SNIST 65
Thread Creation:- There are two ways to create a Thread:

1.By extending Thread class


2.By implementing Runnable interface.

Thread class: Thread class provide constructors and methods to create


and perform operations on a thread. Thread class extends Object class
and implements Runnable interface.

Commonly used Constructors of Thread class:


I. Thread():- Thread t=new Thread();
II. Thread(String name):-
III.Thread(Runnable r)
IV.Thread(Runnable r,String name)

G.Praveen ITDept-SNIST 66
Thread Class Constructors
1. Thread():- Allocates a new Thread Object.
E.g., Thread t=new Thread();

2. Thread(String name) :- Allocates a new thread.


E.g., Thread t= new Thread( “FirstChild”);

3. Thread(Runnable target):-Allocates a new Thread object.


E.g., SecondThread st= new SecondThread();
Thread t=new Thread(st);

4. Thread(Runnable target, String name):-Allocates a new Thread object.


E.g., SecondThread st=new SecondThread();
Thread t= new Thread(st, ”Secondchild”);

G.Praveen ITDept-SNIST 67
5. Thread(ThreadGroup group, String name):- Allocates a new Thread object.

E.g., ThreadGroup tg=new ThreadGroup(“Image Group”);


Thread t1= new Thread(tg,”frist child”);
Thread t2= new Thread(tg,”second
child”);

6. Thread(ThreadGroup group, Runnable target):-Allocates a new thread object.

Where group is the thread group, target is the object whose run method is called.

E.g., ThreadGroup tg=new ThreadGroup(“Image Group”);


SecondThread st= new SecondThread();
Thread t1= new Thread(tg, st);
Thread t2= new Thread(tg, st);

G.Praveen ITDept-SNIST 68
To create a Thread need to override run( ) method available in Thread
class. This method provides an entry point for the thread Following is a
simple syntax of run() method
Syntax:- public void run( )
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
System.out.println("WELCOME IT-DEPT JAVA THREAD...");
}
public static void main(String args[]){ OUTPUT:-
Multi t1=new Multi(); D:\UNIT-4>javac Multi.java
t1.start();
} D:\UNIT-4>java Multi
} thread is running...
WELCOME IT-DEPT JAVA THREAD

G.Praveen ITDept-SNIST 69
2. By implementing Runnable interface:- By using this interface
we will implement a thread by create Thread object explicitely .
EG:- class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3(); OUTPUT:-
Thread t1 =new Thread(m1); C:\praveen\UNIT-4>java Multi3
t1.start(); thread is running...
} }

If there are not extending the Thread class, The class object would not be
treated as a thread object. So you need to explicitly create Thread class
object. We are passing the object of your class that implements Runnable
so that your class run() method may execute.

G.Praveen ITDept-SNIST
Thread Class Methods

Method Description
1.public void run() is used to perform action for a thread.
2.public void start()  starts the execution of the thread.JVM calls the
run() method on the thread.
3.public void sleep(long Causes the currently executing thread to sleep 
miliseconds)
4.public void join() waits for a thread to die.
5.public void join(long waits for a thread to die for the specified
miliseconds): milliseconds.
6.public int getPriority()  returns the priority of the thread.
7.public int setPriority(int changes the priority of the thread.
priority)
8.public String getName() returns the name of the thread.
9.public void changes the name of the thread.
setName(String name)
G.Praveen ITDept-SNIST 71
Method Description
10. public Thread returns the reference of currently executing thread.
currentThread():
11. public int getId() returns the id of the thread.
12. public Thread.State  returns the state of the thread.
getState()
13. public boolean isAlive() tests if the thread is alive.
14. public void yield() causes the currently executing thread object to
temporarily pause and allow other threads to execute.
15. public void suspend() is used to suspend the thread(depricated).
16. public void resume()  is used to resume the suspended thread(depricated).
17. public void stop() is used to stop the thread(depricated).
18. public boolean isDaemon() tests if the thread is a daemon thread.
19. public void interrupt() interrupts the thread.
20. public static boolean  tests if the current thread has been interrupted.
interrupted()

G.Praveen ITDept-SNIST 72
Thread Class Methods:-
1. public static void sleep(long millis, int nanos) throws InterruptedException
Causes the currently executing thread to sleep for the specified
number of milliseconds plus the specified number of
nanoseconds.

2. public static void yield():Causes the currently executing thread object to


temporarily pause and allow other threads to execute.

3.public static Thread currentThread() :Returns a reference to the currently


executing thread object.

4. public final void setName(String name):Changes the name of this thread to be


equal to the argument name.

5. public final int getPriority()    Returns this thread's priority.

6. public final void setPriority(int newPriority)  :-Changes the priority of this


thread.

G.Praveen ITDept-SNIST 73
NOTE 1: The value of new Priority must be within the range
MIN_PRIORITY and MAX_PRIORITY (1 and 10), for default priority,
specify NORM_PRIORITY, which is currently 5. These priorities are defined
as final variables within Thread.

NOTE 2:A thread’s priority is used to decide when to switch from one
running thread to the next. This is called a context switch.
A thread can voluntarily relinquish control.
A thread can be preempted by a higher-priority thread.

public final Thread Group getThreadGroup():- Returns the thread group to


which this thread belongs. This method returns null if this thread has died.

G.Praveen ITDept-SNIST 74
main Thread

In every java program, there is always a thread running internally.


This thread is used by JVM to execute the program statements.

When a Java program starts up, one thread begins running


immediately.

This is usually called the main thread of your program, because it is


the one that is executed when your program begins.

The main thread is important for two reasons:


oIt is the thread from which other “child” threads will be spawned.

oOften it must be the last thread to finish execution because it


performs various shutdown actions.

G.Praveen ITDept-SNIST 75
class One extends Thread{
public void run(){
for(int i=0;i<5;i++){
System.out.println("THread-1 value: "+i);
}}}
class Two extends Thread{
public void run(){
for(int j=10;j>4;j--){
System.out.println("Thread-2 value"+j);
} }}
class Multi2{
public static void main(String sree[]){
One o=new One(); C:\praveen\UNIT-4>java Multi2
o.start(); THread-1 value: 0
Two t=new Two(); THread-1 value: 1
t.start();
}} THread-1 value: 2
THread-1 value: 3
THread-1 value: 4
Thread-2 value10
Thread-2 value9
Thread-2 value8
Thread-2 value7
Thread-2 value6
Thread-2 value5
G.Praveen ITDept-SNIST 76
Difference between “extends Thread” and “implements Runnable” :

1. Both are functionally same.

2. But when we write extends Thread, there is no scope to extend another class, as
multiple inheritance is not supported in java.

class MyClass extends Thread, AnotherClass


//invalid

3. If we write implements Runnable, then still there is scope to extend another class.

class MyClass extends AnotherClass implements Runnable //valid

4.This is definitely advantageous when the programmer wants to use threads and also
wants to access the features of another class.

G.Praveen ITDept-SNIST 77
//Program to display the name of the threads
class Demo extends Thread{
public void run(){
System.out.println(getName());
}}
class Multi4{
public static void main(String args[]){
Thread t=Thread.currentThread();System.out.println("CURRENT Main Thread is:
"+t.getName());
Demo obj1=new Demo();
Demo obj2=new Demo();
Demo obj3=new Demo();
obj1.start();
obj2.start();
obj3.start(); C:\praveen\UNIT-4>java Multi4
} CURRENT Main Thread is: main
} Thread-0
Thread-2
Thread-1

G.Praveen ITDept-SNIST 78
Thread Scheduler:- Thread scheduler in java is the part of the JVM that
decides which thread should run.
The scheduler maintains a pool of threads. When Java thread is started
calling start() method, it joins the pool of waiting threads. For deciding
processor allocation for each waiting thread, the scheduler takes many
aspects into consideration.

1.Priority of thread
2. Waiting time of thread
3. Nature of thread

G.Praveen ITDept-SNIST 79
Java Thread Scheduler Conti…
JVM starts executing a Java program, it creates a few threads for
the execution.
1. main is a method for us, but main is a thread for JVM. The
execution starts with main thread.
2. Garbage collector is a daemon thread that comes into action
before every thread.
3. Event Dispatcher is a thread which will take care of events
raised by the components like click of a button etc.
4. There is one more, Timer thread, which maintains the time for
methods like sleep() etc.

G.Praveen ITDept-SNIST 80
 A thread is started with start() method, the Java thread joins the pool of
waiting threads.
 It does not mean the scheduler should give the processor time
immediately.
 it is guaranteed of getting processor time, but at what time depends on
the decision of the scheduler managed by the OS.
 When a thread joins, the scheduler is executed by the OS and makes a
table of threads' sequence to allocate processor time.
 When a sleep() method is called, the thread is removed from the active
pool, then again the scheduler is executed to make the table as there
comes imbalance in the waiting threads.
 And executed again when the thread joins the pool when
the sleep() time is over. the scheduler executes a number of times when
a thread joins, yields, stops or leaves (when blocked or dies) the pool.

G.Praveen ITDept-SNIST 81
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();
TestMultiPriority1 m3=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start(); D:\UNIT-4>java TestMultiPriority1
m3.start(); running thread name is:Thread-1
} running thread name is:Thread-0
} running thread name is:Thread-2
running thread priority is:1
running thread priority is:10
running thread priority is:5
G.Praveen ITDept-SNIST
D:\UNIT-4>
82
join():-
Often we want the main thread to finish last.
It does not happen automatically.
We uses join( ) to ensure that the main thread is the last to stop.

 final void join( ) throws InterruptedException

This method waits until the thread on which it is called terminates.

G.Praveen ITDept-SNIST 83
Creates Thread t1
Main thread

Calls t1.join()

Main thread suspends


execution Thread t1 terminates

Main thread
resumes

G.Praveen ITDept-SNIST
Daemon Thread:-Daemon thread in java is a service provider thread it
provides services to the user thread. Its life depend on the compassion of user
threads i.e. when all the user threads dies, JVM terminates this thread
automatically.

“Daemon thread is a low priority thread that runs in background to perform


tasks such as garbage collection.”

They can not prevent the JVM from exiting when all the user threads finish
their execution.

JVM terminates itself when all user threads finish their execution

If JVM finds running daemon thread, it terminates the thread and after that
shutdown itself. JVM does not care whether Daemon thread is running or not.

It is an utmost low priority thread.

G.Praveen ITDept-SNIST 85
Methods:-
1.void setDaemon(boolean status): This method is used to mark the current
thread as daemon thread or user thread
Syntax:
public final void setDaemon(boolean on)
parameters: on : if true, marks this thread as a daemon thread.
exceptions: IllegalThreadStateException: if only this thread is active.
SecurityException: if the current thread cannot modify this thread.

Eg:- t1.setDaemon(true) // t1 is a Daemon thread

2. boolean isDaemon(): This method is used to check that current is daemon. It


returns true if the thread is Daemon else it returns false..
Syntax:
public final boolean isDaemon() returns: This method returns true if this thread
is a daemon thread; false otherwise

G.Praveen ITDept-SNIST 86
public class TestDaemon extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemon t1=new TestDaemon();//creating thread
TestDaemon t2=new TestDaemon();
TestDaemon t3=new TestDaemon();

t1.setDaemon(true);//now t1 is daemon thread


OUTPUT:-
t1.start();//starting threads C:\praveen\UNIT-4>java TestDaemon
t2.start(); daemon thread work
t3.start(); user thread work
} user thread work
}

G.Praveen ITDept-SNIST 87
USER DEFINED EXCEPTIONS:-
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
} }
class TestCustomException1{

static void validate(int age)throws InvalidAgeException{


if(age<18)
throw new InvalidAgeException("not valid"); OUTPUT:-
else C:\praveen\UNIT-4>java
System.out.println("welcome to vote"); TestCustomException1
} welcome to vote
rest of the code...
public static void main(String args[]){
try{
validate(23);
}catch(Exception m){System.out.println("Exception occured: "+m);}

System.out.println("rest of the code...");


} } G.Praveen ITDept-SNIST 88

You might also like