0% found this document useful (0 votes)
3 views54 pages

CH-4 Java_notes

Uploaded by

Aditya Sawant
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
3 views54 pages

CH-4 Java_notes

Uploaded by

Aditya Sawant
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 54

Ch-4 Exceptional Handling and Multithreading Marks: 12

_________________________________________________________________

Error

 Errors are mistakes that can make program go wrong.


 Error may be logical or may be typing mistake.
 An error may produce an incorrect output or may terminate the execution
of program abruptly or even may cause the system may crash.

Types of Errors: -

1. Compile time errors


2. Runtime errors

1. Compile time errors:


All syntax errors will be detected and displayed by java compiler and
therefore these errors are known as compile time errors. The most of
common problems are:
 Missing semicolon
 Missing (or mismatch of) bracket in classes & methods
 Misspelling of identifiers & keywords
 Missing double quotes in string
 Use of undeclared variables.
 Bad references to objects.
2. Runtime errors:
Sometimes a program may compile successfully creating the .class file but
may not run properly. Such programs may produce wrong results due to
wrong logic or may terminate due to errors such as stack overflow. When
such errors are encountered java typically generates an error message and
aborts the program. The most common run-time errors are:
 Dividing an integer by zero
 Accessing an element that is out of bounds of an array

Page 1
 Trying to store value into an array of an incompatible class or type
Passing parameter that is not in a valid range or value for method
 Trying to illegally change status of thread
 Attempting to use a negative size for an array
 Converting invalid string to a number
 Accessing character that is out of bound of a string

Exception
What is an Exception?
An exception is an unwanted or unexpected event, which occurs during the
execution of a program i.e at run time, that disrupts the normal flow of the
program’s instructions.
Error vs Exception
Error: An Error indicates serious problem that a reasonable application should
not try to catch.
Exception: Exception indicates conditions that a reasonable application might
try to catch.

 An exception is an event, which occurs during the execution of a program,


that stop the flow of the program's instructions and takes appropriate
actions if handled.
 Exceptional handling mechanism provides a means to detect errors and
throw exceptions, and then to catch exceptions by taking appropriate
actions. Java Exception handles as follow
o Find the problem (Hit the ecxeption)
o Inform that an error has occurred ( throw the Exception)
o Receive the error information(Catch the exception)
o Take corrective action ( Handle the Exception)

Exception Hierarchy
 All exception and errors types are sub classes of class Throwable, which
is base class of hierarchy. One branch is headed by Exception. This class
is used for exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception.Another
branch,Error are used by the Java run-time system(JVM) to indicate errors
having to do with the run-time environment itself(JRE). StackOverflowError
is an example of such an error.

Page 2
1.1 Types of exceptions

There are two types of exceptions in Java:


1)Checked exceptions
2)Unchecked exceptions

Checked exceptions

All exceptions other than Runtime Exceptions are known as Checked exceptions
as the compiler checks them during compilation to see whether the programmer
has handled them or not. If these exceptions are not handled/declared in the
program, you will get compilation error. For example, SQLException, IOException,
ClassNotFoundException etc.

Unchecked Exceptions

Runtime Exceptions are also known as Unchecked Exceptions. These exceptions


are not checked at compile-time so compiler does not check whether the
programmer has handled them or not but it’s the responsibility of the
programmer to handle these exceptions and provide a safe exit. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

Customized Exception Handling : Java exception handling is managed via


five keywords: try, catch, throw, throws, and finally. Briefly, here is how they
work. Program statements that you think can raise exceptions are contained
within a try block. If an exception occurs within the try block, it is thrown. Your
code can catch this exception (using catch block) and handle it in some rational
manner. System-generated exceptions are automatically thrown by the Java
run-time system. To manually throw an exception, use the keyword throw. Any
exception that is thrown out of a method must be specified as such by

Page 3
a throws clause. Any code that absolutely must be executed after a try block
completes is put in a finally block.

Exceptional handling in java by five keywords are as follows:


1. try: This block applies a monitor on the statements written inside it. If
there exist any exception, the control is transferred to catch or finally
block.
Syntax:
try
{
// block of code to monitor for errors
}
2. catch: This block includes the actions to be taken if a particular exception
occurs.
Syntax:
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
3. finally: finally block includes the statements which are to be executed in
any case, in case the exception is raised or not.
Syntax:
finally
{
// block of code to be executed before try block ends
}
4. throw: This keyword is generally used in case of user defined exception, to
forcefully raise the exception and take the required action.
Syntax:
throw throwable instance;
5. throws: throws keyword can be used along with the method definition to
name the list of exceptions which are likely to happen during the execution
of that method. In that case , try … catch block is not necessary in the
code.

Page 4
Syntax:
Type method-name (parameter list) throws exception list
{
// body of method
}
e.g.
public static void main (String a[]) throws IOException
{
----
}
OR

void add() throws Exception-List

Example:
class DemoException
{
public static void main(String args[])
{
try
{
int b=8;
int c=b/0;
System.out.println(“answer=”+c);
}
catch(ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
}
}

Example using throw and throws keyword


import java.lang.*;

Page 5
public class test
{
public static void main(String a[]) throws IOException
{
int n1=10;
int n2=10;
if (n1>n2)
throw new Exception("No.1 is greater");
else
System.out.println("No.2 is greater");
}
}
finally clause
A finally keyword is used to create a block of code that follows a try block. A
finally block of code is always executed whether an exception has occurred or
not. Using a finally block, it lets you run any cleanup type statements that you
want to execute, no matter what happens in the protected code. A finally block
appears at the end of catch block.

Page 6
Example finally Block

In this example, we are using finally block along with try block. This program
throws an exception and due to exception, program terminates its execution but
see code written inside the finally block executed. It is because of nature of
finally block that guarantees to execute the code.
Class ExceptionTest
{
public static void main(String[] args)
{
int a[] = new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}

Out of try

finally is always executed.

Exception in thread main java. Lang. exception array Index out of bound
exception.

You can see in above example even if exception is thrown by the program, which
is not handled by catch block, still finally block will get executed.

Example: Finally Block

finally block executes in all the scenario whether exception is caught or not. In
previous example, we use finally where exception was not caught but here
exception is caught and finally is used with handler.
class Demo
{
public static void main(String[] args)
{
int a[] = new int[2];
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}

Page 7
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught");
}
finally
{
System.out.println("finally is always executed.");
}
}
}

Exception caught

finally is always executed


Example using finally keyword

import java.lang.*;
public class testfinally
{
public static void main(String a[]) throws IOException
{
System.out.println(""Start of execution)
int a, b, c;
try
{
a=Interger.parseInt(arg[0]);
a=Interger.parseInt(arg[1]);
c=a/b;
System.out.println("Answer is"+c);
}
catch(Exception e)
{
System.out.println(e)
}
finally
{
System.out.println("Finally will always execute");
}

Page 8
System.out.println("Execution complete here");
}
}

Throw Throws
Whenever we want to force an when we know that a particular
exception then we use throw exception may be thrown or to pass a
keyword. possible exception then we use
throws keyword.
"Throw" is used to handle user- JVM handles the exceptions which are
defined exception. specified by "throws".

It can also pass a custom message to Point to note here is that the Java
your exception handling module. compiler very well knows about the
exceptions thrown by some methods
so it insists us to handle them.
Throw keyword can also be used to We can also use throws clause on
pass a custom message to the the surrounding method instead of
exception handling module i.e. the try and catch exception handler.
message which we want to be
printed.

Throw is used to through exception Throws is used for to throws


system explicitly. exception means throws ioexception
and servletexception and etc.

Throw is used to actually throw the Whereas throws is declarative for the
exception. method. They are not
interchangeable.

Page 9
It is used to generate an exception. It is used to forward an exception.
Cannot throw multiple exceptions Can declare multiple exceptions
Syntax: Syntax:
 throw is followed by an object  throws is followed by a class
(new type)  and used with the method
 used inside the method signature

Built-in Exception
 Java exceptions are the exceptions that are caused by run time error in the
program. Some common exceptions in java are as follows:
Sr. Built-in Exception Explaination
No.
1 ArithmeticException It is caused by Maths error sush as
divide by 0.
2 ArrayIndexOutOfBoundsException It is caused when array index is out of
bound
3 ArrayStoreException It is caused when a program tries to
store wrong type of data in an array.
4 FileNotFoundException It is caused by an attempt to access a
non-existent file.
5 IOException It is caused by general IO failure such
as inability to read from the file.
6 NullPointerException It is caused by referencing a null object

7 NumberFormatException It is caused when a conversion


between string and number fails.
8 OutOfMemoryException It is caused when there is not enough
memory to allocate a new object.
9 SecurityException It is caused when an applet tries to
perform an action not allowed by the
browser security setting.
10 StackOverFlowException It is caused when system runs out of
space.
11 StringIndexOutOfBoundsException It is caused when a program attempts
to access non-existent character in a
Page 10
string.

Nested Try

The nested try is used to implement multiple try statements in a single block of
main method.
Syntax: -
Try
{
----
----
Try
{
----
----
}
}
Example:
class nested_try_block
{
public static void main(String[] args)
{
try
{
int arr[]={5,0,1,2};
try
{
int x = arr[3]/arr[1]; //2/0
}
catch(ArithmeticException ae)
{
System.out.println(" You can not divide by zero");
}

Page 11
arr[8]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}

Chained Exception
 Whenever in a program first exception causes another exception to occur it
is called a chained exception.
 Exception chaining is also known as nesting exception and it is technique
for handling the exception which occurs one after the other that is most of
the time given by an application in response to an exception by throwing
another exception.
 Typically, the second exception caused by the first exception therefore
chained exception helped programmer to know when one exception causes
another.
 The methods and constructor in throwable that support chain exception.

More Examples on Exception Handling:

Java Exception Handling examples

Example 1: Arithmetic exception

Class: Java.lang.ArithmeticException
This is a built-in-class present in java.lang package. This exception occurs when
an integer is divided by zero.

class Example1
{
public static void main(String args[])
{
try{
Page 12
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result: "+output);
}
catch(ArithmeticException e){
System.out.println ("You Shouldn't divide a number by zero");
}
}
}
Output of above program:

You Shouldn't divide a number by zero


Explanation: In the above example I’ve divided an integer by a zero and
because of this ArithmeticException is thrown.

Example 2: ArrayIndexOutOfBounds Exception

Class: Java.lang.ArrayIndexOutOfBoundsException
This exception occurs when you try to access the array index which does not
exist. For example, If array is having only 5 elements and we are trying to display
7th element then it would throw this exception.

class ExceptionDemo2
{
public static void main(String args[])
{
try{
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}
Output:

ArrayIndexOutOfBounds
In the above example the array is initialized to store only 10 elements indexes 0
to 9. Since we are try to access element of index 11, the program is throwing this
exception.

Example 3: NumberFormat Exception

Class: Java.lang.NumberFormatException

This exception occurs when a string is parsed to any numeric variable.

Page 13
For example, the statement int num=Integer.parseInt ("XYZ"); would
throw NumberFormatException because String “XYZ” cannot be parsed to int.

class ExceptionDemo3
{
public static void main(String args[])
{
try{
int num=Integer.parseInt ("XYZ") ;
System.out.println(num);
}catch(NumberFormatException e){
System.out.println("Number format exception occurred");
}
}
}
Output:

Number format exception occurred


Example 4: StringIndexOutOfBound Exception

Class: Java.lang.StringIndexOutOfBoundsException

 An object of this class gets created whenever an index is invoked of a string,


which is not in the range.
 Each character of a string object is stored in a particular index starting from
0.
 To get a character present in a particular index of a string we can use
a method charAt(int) of java.lang.String where int argument is the index.
E.g

class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="beginnersbook";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}
Output:

13
StringIndexOutOfBoundsException!!

Page 14
Exception occurred because the referenced index was not present in the String.

Example 5: NullPointer Exception

Class: Java.lang.NullPointer Exception


An object of this class gets created whenever a member is invoked with a “null”
object.

class Exception2
{
public static void main(String args[])
{
try{
String str=null;
System.out.println (str.length());
}
catch(NullPointerException e){
System.out.println("NullPointerException..");
}
}
}
Output:

NullPointerException..
Here, length() is the function, which should be used on an object. However in the
above example String object str is null so it is not an object due to
which NullPointerException occurred.

Example:

public class throws_Example1


{
int division(int a, int b) throws ArithmeticException
{
int t = a/b;
return t;
}
public static void main(String args[])
{
throws_Example1 obj = new throws_Example1();

System.out.println(obj.division(15,0));
}
}
Example:

public class ThrowExample


Page 15
{
static void checkEligibilty(int stuage, int stuweight)
{
if(stuage<12 && stuweight<40)
{
throw new ArithmeticException("Student is not eligible for
registration");
}
else
{
System.out.println("Student Entry is Valid!!");
}
}

public static void main(String args[])


{
System.out.println("Welcome to the Registration process!!");
checkEligibilty(10, 35);
System.out.println("Have a nice day..");
}
}

Example:
import java.io.*;
class MyOwnException extends Exception
{
public MyOwnException(String msg)
{
super(msg);
}
}
class EmployeeTest
{
public static void main(String[] args) throws IOException

Page 16
{
DataInputStream d=new DataInputStream(System.in);
try
{ System.out.println("Enter age:");
int a=Integer.parseInt(d.readLine());
if(a < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
catch (MyOwnException e)
{ e.printStackTrace();
//System.out.println("Error");
}
/* catch (IOException e)
{
e.printStackTrace();
} */
}
}

Example:
import java.io.*;
class MyOwnException extends Exception
{
public MyOwnException(String msg)
{
super(msg);
}
}
class EmployeeTest
{

Page 17
public static void main(String[] args) throws IOException
{
DataInputStream d=new DataInputStream(System.in);
try
{ System.out.println("Enter age:");
int a=Integer.parseInt(d.readLine());
if(a < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
catch (MyOwnException e)
{ e.printStackTrace();
//System.out.println("Error");
}

/* catch (IOException e)
{
e.printStackTrace();
} */
}
}

Program to throw user defined exception by accepting a number from


user and throw an exception if the number is not positive number.
import java.lang.*;
import java.io.*;
class PException extends Exception
{
PException(String msg)
{
super(msg);
}
}

class posex
{
public static void main(String args[])
{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
Page 18
int n;
try
{
System.out.println("Enter any Number");
n=Integer.parseInt(bf.readLine());
if(n>0)
{
System.out.println(“You are Entered Positive Number, please entered Negative
number for exception ");
}
else
{
throw new PException("Entered Number is Negative Number");
}
}
catch(PException e)
{System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);}
}
}
Output:
Enter any Number 3
You are Entered Positive Number, please entered Negative number for exception
Enter any Number -3
PException: Entered Number is Negative Number

Program to accept a password from the user and throw 'authentication


Failure' exception if the password is incorrect.
import java.io.*;
import java.lang.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}

class passwordau
{
public static void main(String args[])
{
DataInputStream d=new DataInputStream(System.in);
String s1=new String();
String s2=new String();
try
{

Page 19
System.out.println("Enter to set the password");
s1=d.readLine();
System.out.println("Re-Enter the password");
s2=d.readLine();

if(s1.equals(s2))
{
System.out.println("Password Validated");
}
else
{
throw new MyException("Authentication Failure");
}
}

catch(MyException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
Enter to set the password abc
Re-Enter the password abc
Password Validated
Enter to set the password abc
Re-Enter the password xyz
MyException: Authentication Failure

Program to accept a number from the user and throw an exception if


the number is not an even number.
import java.io.*;
import java.lang.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}

class oddeven
{
public static void main(String args[])
{
DataInputStream d=new DataInputStream(System.in);
int n;

Page 20
try
{
System.out.println("Enter a Number");
n=Integer.parseInt(d.readLine());
if(n%2==0)
{
throw new MyException("Number is EVEN");
}
else
{
throw new MyException("Number is ODD");
}
}

catch(MyException e)
{
System.out.println(e);
}

catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
Enter a Number 2
MyException: Number is EVEN
Enter a Number 3
MyException: Number is ODD

Program to accept a string from the user and throw an exception if the
string is not containing character 'a'.
import java.io.*;
import java.lang.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class StringB
{
public static void main(String args[])
{
DataInputStream d=new DataInputStream(System.in);
String s;
try

Page 21
{
int len;
char ch;
System.out.println("Enter the String");
s=d.readLine();
if(s.indexOf("a")!=-1)
{
System.out.println("Your String contains 'a'");
}
else
{
throw new MyException("Your String does not contains 'a'");
}
}

catch(MyException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
Enter the String java
Your String contains 'a'
Enter the String ops
MyException: Your String does not contains 'a'

Write a program to throw a user defined exception “String Mismatch


Exception” if two strings are not equal. (ignore case).
import java.io.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class ExceptionTest
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
String s1,s2;
try
{

Page 22
System.out.println("Enter String one and String two ");
s1=br.readLine();
s2=br.readLine();
if(s1.equalsIgnoreCase(s2)) // any similar method which give
correct result
{
System.out.println("String Matched");
}
else
{
throw new MyException("String Mismatch Exception");
}
}
catch(MyException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}

Write a program to throw a user defined exception as ‘Invalid Age’, if


age entered by the user is less than eighteen. Also mention any two
common java exceptions and their cause.
import java.lang.Exception;
import java.io.*;
class myException extends Exception
{
myException(String msg)
{
super(msg);
}
}
class agetest
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("enter the age : ");
int n=Integer.parseInt(br.readLine());
if(n < 18 )
throw new myException("Invalid Age");
else
System.out.println("Valid age");
}

Page 23
catch(myException e)
{
System.out.println(e.getMessage());
}
catch(IOException ie)
{}
}
}

Write a java program to accept email address of a user and throw a


user defined exception InvalidEmailException if it starts with digit or
does not contain @ symbol.
import java.io.*;
class myException extends Exception
{
myException(String msg)
{
super(msg);
}
}

class test
{
public static void main(String args[])
{
BufferedReader bin=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter E-mail Address: ");
String s1=bin.readLine();
char c='@';
if(s1.contains("@"))
{
System.out.println("ValidEmail ");
}
else
{
throw new myException("InvalidEmailException");
}
}
catch(myException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}

Page 24
Output:

Program to accept string from a user, if its length is less than 6, then
throw user defined exception “Invalid String” otherwise display the
string in uppercase

import java.io.*;
import java.lang.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}

class test
{
public static void main(String args[])
{
DataInputStream d=new DataInputStream(System.in);
String s1=new String();

try
{
System.out.println("Enter String");
s1=d.readLine();
int n=6;
if(s1.length() >= n)
{
System.out.println(s1.toUpperCase());
}
else
{
throw new MyException("Invalid String");
}
}

catch(MyException e)
Page 25
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
C:\Java\jdk1.7\bin>java test
Enter String
hello
MyException: Invalid String

C:\Java\jdk1.7\bin>java test
Enter String
computer
COMPUTER

Java Program that contains a class Account with acc_no, name and
balance as field. Accept(), withdraw(), deposite() as methods. If
balance<500 then raise exception “MinimumBalanceException”. If name
contains digits then raise exception ”invalidNameException”.
Sol:
import java.io.*;
import java.lang.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}

class test
{
int balance;
int amount;
void accept(String s)
{
String s1="Hello";
String s2;
try
{
s2=s;
if(s1.equals(s2))
{
System.out.println("Valid Name");
}
else

Page 26
{
throw new MyException("InvalidNameException");
}
}
catch(MyException e)
{
System.out.println(e);
}
} //End of accept method

void deposit(int n)
{
amount=n;
balance=balance+amount;
System.out.println("Total Balance="+balance);
} //end of deposit

void withdraw(int w)
{
amount=w;
try
{
balance=balance-amount;
if(balance<=500)
{
throw new MyException("MinumumBalanceException");
}
else
{
System.out.println("Balance="+balance);
}
}
catch(MyException e)
{
System.out.println(e);
}
} //end of withdraw

public static void main(String args[])


{
test t1=new test();
t1.accept("Hello");
t1.deposit(2000);
t1.withdraw(1500);
}
}
Output:

Page 27
Create a class student with attributes rno, name , age and class.
Initialize values through parameterize constructor. If age of student is
not in between 15 to 21 then generate user defined exception as
“InvalidAgeException”. Similarly if name contains special symbols or
digits then raise exception as “InvalidNameException”. Handle these
exceptions.
class InvalidAgeException extends Exception{}
class InvalidNameException extends Exception{}
class Student
{
int RollNo, Age;
String Name,Course;
Student(int rno, String name, int age, String course)
{
try
{
RollNo = rno;
Name = name;
Age = age;
Course = course;
if(Age<15 || Age>21)
throw new InvalidAgeException();
for(int i=0; i<Name.length(); i++)
if(Character.isDigit(Name.charAt(i)))
throw new InvalidNameException();
}
catch(InvalidAgeException e)
{
System.out.println("Age Not Within The Range");
}
catch(InvalidNameException e)
{
System.out.println("Name not valid");
}
}
public String toString()
{
return "Roll No:"+RollNo+
"\nName :"+Name+

Page 28
"\nAge :"+Age+
"\nCourse :"+Course;
}
}
class StudentExceptionDemo
{
public static void main(String args[])
{
Student s1 = new Student(1,"Ram",17,"Java Programming");
System.out.println(s1);
Student s2 = new Student(2,"John",28,"C++ Programming");
System.out.println(s2);
Student s3 = new Student(3,"Akbar15",19,"C++ Programming");
System.out.println(s3);
}
}

Output:
Roll No:1
Name :Ram
Age :17
Course :Java Programming
Age Not Within The Range
Roll No:2
Name :John
Age :28
Course :C++ Programming
Name not valid
Roll No:3
Name :Akbar15
Age :19
Course :C++ Programming

Multithreading Programming

 It is technique that allows a program or process to execute many task


concurrently.
 It allows process to run its task in parallel mode on single processor
system.
 In multithreading concept several multiple light weight processes run in a
single process by single processor.
 For e.g. When work with word processor you can perform many different
task such as printing, spell check and so on. Multithreading software treats
each process as a separate program.

Page 29
Thread
 Thread is a smallest unit of executable code or a single task is also called
as thread.
 Each tread has its own local variable, program counter and lifetime.
 A thread is similar to program that has a single flow of control.
 It has beginning, body and end executes command sequentially.

Life Cycle of Thread

Page 30
Thread Life Cycle Thread has five different states throughout its life.
1) Newborn State
When a thread object is created it is said to be in a new born state. When
the thread is in a new born state it is not scheduled running from this state
it can be scheduled for running by start() or killed by stop(). If put in a
queue it moves to runnable state.

A NEW Thread (or a Born Thread) is a thread that's been created but not yet
started. It remains in this state until we start it using the start() method.
The following code snippet shows a newly created thread that's in the NEW state:
Runnable runnable = new NewState();
Thread t = new Thread(runnable);

2) Runnable State
It means that thread is ready for execution and is waiting for the
availability of the processor i.e. the thread has joined the queue and is
waiting for execution. If all threads have equal priority, then they are given
time slots for execution in round robin fashion. The thread that relinquishes
control joins the queue at the end and again waits for its turn. A thread can
relinquish the control to another before its turn comes by yield().

Page 31
Runnable runnable = new NewState();
Thread t = new Thread(runnable); t.start();
3) Running State
It means that the processor has given its time to the thread for execution.
The thread runs until it relinquishes control on its own or it is pre-empted
by a higher priority thread.
4) Blocked State
A thread can be temporarily suspended or blocked from entering into the
runnable and running state by using either of the following thread method.
o suspend() : Thread can be suspended by this method. It can be
rescheduled by resume().
o wait(): If a thread requires to wait until some event occurs, it can be
done using wait method and can be scheduled to run again by
notify().
o sleep(): We can put a thread to sleep for a specified time period using
sleep(time) where time is in ms. It reenters the runnable state as
soon as period has elapsed /over.
5) Dead State
Whenever we want to stop a thread form running further we can call its
stop(). The stop() causes the thread to move to a dead state. A thread will
also move to dead state automatically when it reaches to end of the
method. The stop method may be used when the premature death is
required

New/Start:

This is the state the thread is in after the Thread instance has been created, but the
start() method has not been invoked on the thread. It is a live Thread object, but not
yet a thread of execution. At this point, the thread is considered not alive.

Runnable:

This means that a thread can be run when the time-slicing mechanism has CPU
cycles available for the thread. Thus, the thread might or might not be running at any

Page 32
moment, but there’s nothing to prevent it from being run if the scheduler can arrange
it. That is, it’s not dead or blocked.

Running:

This state is important state where the action is. This is the state a thread is in when
the thread scheduler selects it (from the runnable pool) to be the currently executing
process. A thread can transition out of a running state for several reasons, including
because "the thread scheduler felt like it". There are several ways to get to the
runnable state, but only one way to get to the running state: the scheduler chooses a
thread from the runnable pool of thread.

Blocked:

The thread can be run, but something prevents it. While a thread is in the blocked
state, the scheduler will simply skip it and not give it any CPU time. Until a thread
reenters the runnable state, it won’t perform any operations. Blocked state has some
sub-states as below,

 Blocked on I/O: The thread waits for completion of blocking operation. A thread can enter this
state because of waiting I/O resource. In that case, the thread sends back to runnable state after
the availability of resources.

 Blocked for join completion: The thread can come in this state because of waiting for the
completion of another thread.

 Blocked for lock acquisition: The thread can come in this state because of waiting for acquire
the lock of an object.

Dead:

A thread in the dead or terminated state is no longer schedulable and will not receive
any CPU time. Its task is completed, and it is no longer runnable. One way for a task
to die is by returning from its run( ) method, but a task’s thread can also be
interrupted, as you’ll see shortly.

Thread should be in any one state of above and it can be move from one state to
another by different methods and ways.

Q) With proper syntax and example explain following thread methods:

Page 33
With proper syntax and example explain following thread methods:

1) suspend() - syntax : public void suspend() This method puts a thread in


suspended state i.e blocked and can be resumed using resume() method.

2) resume() syntax : public void resume() This method resumes a thread which
was suspended using suspend() method.The thread enter in active state i.e
Runnable state.
3) yield() syntax : public static void yield() The yield() method causes the
currently executing thread object to temporarily pause and move to runnable
state from running state and allow other threads to execute.

4) wait() and notify() syntax : public final void wait() This method causes the
current thread to wait until some event occurs and another thread invokes the
notify() method or the notifyAll() method for this object.

5) stop() syntax: void stop() Used to kill the thread. It stops thread.

6)sleep() syntax: public static void sleep(long millis) throws


InterruptedException We can put a thread to sleep for a specified time period

Page 34
using sleep(time) where time is in ms. It reenters the runnable state as soon as
period has elapsed /over.

Eg.
class sus extends Thread implements Runnable
{
static Thread th;
float rad,r;
public sus()
{
th= new Thread();
th.start();
}
public void op()
{
System.out.println("\nThis is OP");
if(rad==0)
{
System.out.println("Waiting for input radius");
Try
{
wait();
}
catch(Exception ex)
{

}
}
}
public void ip()
{
System.out.println("\nThis is IP");
r=7;
rad= r;

Page 35
System.out.println(rad);
System.out.println("Area = "+3.14*rad*rad);
notify();
}
public static void main(String arp[])
{
Try
{
sus s1 = new sus();
System.out.println("\nReady to go");
Thread.sleep(2000);
System.out.println("\nI am resuming");
th.suspend();
Thread.sleep(2000);
th.resume();
System.out.println("\nI am resumed once again");
s1.op();
s1.ip();
s1.op();
}
catch(Exception e)
{
}
}
}

Java Thread Priority in Multithreading


In a Multi threading environment, thread scheduler assigns processor to a
thread based on priority of thread. Whenever we create a thread in Java, it
always has some priority assigned to it. Priority can either be given by JVM
while creating the thread or it can be given by programmer explicitly.
Accepted value of priority for a thread is in range of 1 to 10. There are 3
static variables defined in Thread class for priority.
public static int MIN_PRIORITY: This is minimum priority that a thread
can have. Value for this is 1.

Page 36
public static int NORM_PRIORITY: This is default priority of a thread if
do not explicitly define it. Value for this is 5.
public static int MAX_PRIORITY: This is maximum priority of a thread.
Value for this is 10.
Get and Set Thread Priority:
1. public final int getPriority(): java.lang.Thread.getPriority() method
returns priority of given thread.
2. public final void setPriority(int
newPriority): java.lang.Thread.setPriority() method changes the
priority of thread to the value newPriority. This method throws
IllegalArgumentException if value of parameter newPriority goes beyond
minimum(1) and maximum(10) limit.

Creating Threads
There are two ways to create threads in java:
1. By extending thread class
o User specified thread class is created by extending the class ‘Thread’
and overriding its run() method.
o For creating a thread a class has to extends the thread class that is
java.lang.Thread
o Syntax: -
Declare class as extending thread
class Mythread extends Thread
{
____
------
}

1.1.1 Implementing the Runnable Interface

The easiest way to create a thread is to create a class that


implements the runnable interface. After implementing runnable
interface, the class needs to implement the run() method.

Page 37
1.1.2 Run Method Syntax:

public void run()

 It introduces a concurrent thread into your program. This


thread will end when run() method terminates.
 You must specify the code that your thread will execute
inside run() method.
 run() method can call other methods, can use other classes
and declare variables just like any other normal method.
 Note: If you are implementing Runnable interface in your
class, then you need to explicitly create a Thread class
object and need to pass the Runnable interface
implemented class object as a parameter in its constructor.

class MyThread implements Runnable


{
public void run()
{
System.out.println(" thread started running..");
}
}

class MyThreadDemo_interface
{
public static void main(String args[])
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
Develop a program to create two threads such that one thread will
print odd no. and another thread will print even no. between 1-20

Page 38
class odd extends Thread
{
public void run()
{
for(int i=1;i<=20;i=i+2)
{
System.out.println("ODD="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");
}
}
}
}
class even extends Thread
{
public void run()
{
for(int i=0;i<=20;i=i+2)
{
System.out.println("EVEN="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");
}
}

Page 39
}
}
class oddeven2
{
public static void main(String arg[])
{
odd o=new odd();
even e=new even();
o.start();
e.start();
}
}

Develop a program to create three threads such that one thread will
print odd no. and another thread will print even no. and third thread
will print all no. between 1-10 and set Priority.
class odd extends Thread
{
public void run()
{
for(int i=1;i<=10;i=i+2)
{
System.out.println("ODD="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");
}
}

Page 40
}
}
class even extends Thread
{
public void run()
{
for(int i=0;i<=10;i=i+2)
{
System.out.println("EVEN="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");
}
}
}
}
class allnumbers extends Thread
{
public void run()
{
for(int i=0;i<=10;i++)
{
System.out.println("All numbers="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");

Page 41
}
}
}
}
class oddeven1
{
public static void main(String arg[])
{
odd o=new odd();
even e=new even();
allnumbers a=new allnumbers();
o.setPriority(6);
e.setPriority(4);
a.setPriority(8);
o.start();
e.start();
a.start();
}
}
Write a program to create two threads; one to print numbers in original
order and other to reverse order from 1 to 50.

class original extends Thread


{
public void run()
{
try
{
for(int i=1; i<=50;i++)
{
System.out.println("\t First Thread="+i);
Thread.sleep(300);
}
}

Page 42
catch(Exception e)
{}
}
}
class reverse extends Thread
{
public void run()
{
try
{
for(int i=50; i>=1;i--)
{
System.out.println("\t Second Thread="+i);
Thread.sleep(300);
}
}
catch(Exception e)
{
}
}
}
class orgrev
{
public static void main(String args[])
{
new original().start();
new reverse().start();
System.out.println("Exit from Main");
}
}

Q. Write a program to create two threads one to print odd numbers


from 1 to 10 and other to print even numbers from 11 to 20

Page 43
import java.lang.*;
class even extends Thread
{
public void run()
{
try
{
for(int i=0;i<=10;i=i+2)
{
System.out.println("\tEven thread="+i);
Thread.sleep(300);
}
}
catch(InterruptedException e)
{}
}
}

class odd extends Thread


{
public void run()
{
try
{
for(int i=1;i<=10;i=i+2)
{
System.out.println("\todd thread="+i);
Thread.sleep(300);
}}
catch(InterruptedException e)
{
}
}
}

Page 44
class evenodd
{
public static void main(String args[])
{
new even().start();
new odd().start();
System.out.println("Exit from main");
}
}

2. Creating thread using Runnable Interface


The Runnable interface should be implemented by any class whose instances
are intended to be executed by a thread. Runnable interface have only one
method named run().

public void run(): is used to perform action for a thread.


start() method of Thread class is used to start a newly created thread. It
performs following tasks:

o A new thread starts(with new callstack).

o The thread moves from New state to the Runnable state.

o When the thread gets a chance to execute, its target run() method will run.
For E.g.
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

Write a thread program for implementing the “Runnable


interface‟. (8 Marks) Or program to print even numbers from 1 to 20

Page 45
using Runnable Interface

class mythread implements Runnable


{
public void run()
{
System.out.println("Even numbers from 1 to 20 : ");
for(int i= 1 ; i<=20; i++)
{
if(i%2==0) System.out.print(i+ " ");
}
}
}
class test
{
public static void main(String args[])
{
mythread mt = new mythread();
Thread t1 = new Thread(mt);
t1.start();
}
}
What is synchronization? When do we use it? Explain
synchronization of two threads.

 When two or more threads need 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 by which this is achieved is called synchronization.
Synchronization used when we want to –
1) prevent data corruption.
2) prevent thread interference.
3) Maintain consistency If multiple threads require an access to an
Object.

Page 46
Program based on synchronization:
class Callme
{
void call(String msg)
{
System.out.print("[" +msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
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();
}
public void run()
{
synchronized(target)
{

Page 47
target.call(msg);
}
}
class Synch
{
public static void main(String args[])
{
Callme target=new Callme();
Caller ob1=new Caller(target,"Hello");
Caller ob2=new Caller(target,"Synchronized");
try
{
ob1.t.join();
ob2.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
}
}

Thread Priority

 Threads in java are sub programs of main application program and share
the same memory space. They are known as light weight threads.
 A java program requires at least one thread called as main thread. The
main thread is actually the main method module which is designed to
create and start other threads.
 A Thread is similar to a program that has a single flow of control. Every
thread has a beginning, a body and an end.

Page 48
 However, thread is not a program, but runs within a program.
 Thread Priority: In java each thread is assigned a priority which affects
the order in which it is scheduled for running. Threads of same priority are
given equal treatment by the java scheduler.
 The thread class defines several priority constants as: -
MIN_PRIORITY =1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
 Thread priorities can take value from 1-10.
1) setPriority () This method is used to assign new priority to the
thread
Syntax: Thread.setPriority (priority value);
2) getPriority() It obtain the priority of the thread and returns integer
value.
Syntax: int Thread.getPriority ();

Intercrosses Communication

 Java provide benefits of avoiding thread pooling using inter-thread


communication.
 The wait(), notify(), and notifyAll() methods of Object class are used for
this purpose. These method are implemented as final methods in Object,
so that all classes have them. All the three method can be called only from
within a synchronized context.

 wait() tells calling thread to give up monitor and go to sleep until some other
thread enters the same monitor and call notify.
 notify() wakes up a thread that called wait() on same object.
 notifyAll() wakes up all the thread that called wait() on same object.
import java.util.Scanner;
public class threadexample
{
public static void main(String[] args)
throws InterruptedException
{
final PC pc = new PC();

Page 49
// Create a thread object that calls pc.produce()
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
};

// Create another thread object that calls


// pc.consume()
Thread t2 = new Thread(new Runnable()
{

public void run()


{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

// Start both threads


t1.start();
t2.start();

// t1 finishes before t2
t1.join();
t2.join();
}

// PC (Produce Consumer) class with produce() and


// consume() methods.
public static class PC
{
// Prints a string and waits for consume()

Page 50
public void produce()throws InterruptedException
{
// synchronized block ensures only one thread
// running at a time.
synchronized(this)
{
System.out.println("producer thread running");

// releases the lock on shared resource


wait();

// and waits till some other method invokes notify().


System.out.println("Resumed");
}
}

// Sleeps for some time and waits for a key press. After key
// is pressed, it notifies produce().
public void consume()throws InterruptedException
{
// this makes the produce thread to run first.
Thread.sleep(1000);
Scanner s = new Scanner(System.in);

// synchronized block ensures only one thread


// running at a time.
synchronized(this)
{
System.out.println("Waiting for return key.");
s.nextLine();
System.out.println("Return key pressed");

// notifies the produce thread that it


// can wake up.
notify();

// Sleep
Thread.sleep(2000);
}
}
}
}

//example of java synchronized method


class Table
{
synchronized void printTable(int n){//synchronized method

Page 51
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

}
}

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run(){
t.printTable(100);
}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run()
{
t.printTable(5);
}
}

public class TestSynchronization2


{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t2.start();
t1.start();
}
}

Deadlock

Page 52
 Deadlock is a situation of complete Lock, when no thread can complete its
execution because lack of resources.
 In the diagram, Thread 1 is holding a resource R1, and need another
resource R2 to finish execution, but R2 is locked by Thread 2, which needs
R3, which in turn is locked by Thread 3.
 Hence none of them can finish and are stuck in a deadlock.

public class TestThread {


public static Object Lock1 = new Object();
public static Object Lock2 = new Object();

public static void main(String args[]) {


ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
T2.start();
}
private static class ThreadDemo1 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 1: Holding lock 1...");

try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}

Page 53
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}

Page 54

You might also like