Sie sind auf Seite 1von 43

UNIT-4

Java Exception:

Exception:

 Dictionary meaning is abnormal condition


 An exception is an event that terminates the programs abnormally is called as an
exception.These exceptions occurred at runtime execution
 An unexpected event that terminates the flow of the programs.
 An exception is an event that terminates the normal flow of program is called as
exception. When an exception occurred (raised) the rest of the code will not executed.

To overcome these exception handle the exceptions.

How to handle the exception?

Exception handling:

An exception is an event that terminates the program normally and remaining code
will executed.

Main objective:

The main objective of the handling the exception is to get the normal termination of the
program and rest of code will executed.

To handling the exception have two approaches:


1. try-catch block
2. throws

How many keywords used to handle the exception in java?

Ans: Five

They are: 1) Try 2) catch 3) finally 4) throw 5) throws


1
Page

Prof. Raju R. Vathari


UNIT-4

There are two types of exceptions in java:

1. Un-checked Exception:
 An unchecked exception is an exception while execution the program the
compiler unable to check the exception is called as unchecked exception.
 This exception occurred at runtime.
 If the program is contains unchecked exception, but code is compiled and at
runtime JVM display the exception.

Examples for the unchecked exceptions are:

1. ArithmeticExcepption.
2. NumberNotFoundException.
3. NullPointerException.
4. ArrayIndexOutOfBoundsException.etc..
Examples 1:ArithmeticException

class JavaException
{
public static void main(String args[])
{
System.out.println("Hi JAVA-1 ");
System.out.println("Hi JAVA-2 ");
System.out.println(10/0);
System.out.println("Hi JAVA-3 ");
System.out.println("Hi JAVA-4 ");
}
}
2
Page

Prof. Raju R. Vathari


UNIT-4

In above example contains there are five statements and while executing the above
code the compiler unable to check the exception , code will compiled successfully
and at runtime JVM display the exception.
 At the statement line no 3 will have an exception
System.out.println(10/0); //ArithmeticExcepption.
 At statement-1 and statement -2 will executed and rest of code will not
executed. see below lines:

C:\Users\Admin\Desktop\Java Exceptions>javac JavaException.java


C:\Users\Admin\Desktop\Java Exceptions>java JavaException
Hi JAVA-1
Hi JAVA-2
Exception in thread "main" java.lang.ArithmeticException: / by zero
at JavaException.main(JavaException.java:7)

If we are dividing any number by zero that produces the exception at runtime that is
ArithmeticException.

Example 2:ArrayIndexOutOfBoundsException

public class MyClass


{
public static void main(String[] args)
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
System.out.println("Something went wrong.");
}
}

After Executing we get an exception is:

C:\Users\Admin\Desktop\Java Exceptions>javac MyClass.java

C:\Users\Admin\Desktop\Java Exceptions>java MyClass

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:


10
3

at MyClass.main(MyClass.java:6)
Page

Prof. Raju R. Vathari


UNIT-4

Example 3: NullPointerException

class NullPoiter
{
public static void main (String[] args)
{
String str1 = null;
String str2 = “JAVA”;
if (str1.equals(str2))
{
System.out.print("Same");
}
else
{
System.out.print("Not Same");
}
}
}

After execution:

C:\Users\Admin\Desktop\Java Exceptions>javac NullPoiter.java

C:\Users\Admin\Desktop\Java Exceptions>java NullPoiter

Exception in thread "main" java.lang.NullPointerException

at NullPoiter.main(NullPoiter.java:13)

Example 4: NumberFormatException:

class NumberFormatException
{
public static void main (String[] args)
{
// Initializing String variable with null value
String str = null;
int i=Integer.parseInt(str);
System.out.println(i);
}
}
4
Page

Prof. Raju R. Vathari


UNIT-4

After Executing:

C:\Users\Admin\Desktop\Java Exceptions>javac NumberFormatException.java


C:\Users\Admin\Desktop\Java Exceptions>java NumberFormatException
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at NumberFormatException.main(NumberFormatException.java:8)

The above examples are the unchecked exceptions caught at runtime.

2. Checked Exception:
 The checked exceptions are the exceptions which are checked by the compiler
it is called as checked exception, code will not compiled.
 If the program is containing the checked exception code is not executed.
Example is :IOException, SQLException etc. Checked exceptions are checked
at compile-time.

To handle this type of exception we have to approaches:

1.try-catch block
2.throws

Example1: FileNotFoundException:

import java.io.*;
class IOExceptions
{
public static void main(String[] args)
{
FileReader file = new FileReader("C:\\Desktop\\a.txt");
}
}

After executing:

C:\Users\Admin\Desktop\Java Exceptions>javac IOExceptions.java


IOExceptions.java:7: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown
FileReader file = new FileReader("C:\\test\\a.txt");
1 error
5
Page

Prof. Raju R. Vathari


UNIT-4

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is why
we use exception handling.

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally. It
means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by
finally block later.

finally The "finally" block is used to execute the important code of the program. It
is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an


exception. It specifies that there may occur an exception in the method. It is
always used with method signature.
6
Page

Prof. Raju R. Vathari


UNIT-4

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

String s=null;
System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

The wrong formatting of any value may occurNumberFormatException. Suppose we have a


string variable that has characters, converting this variable into digit will
occurNumberFormatException.

String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException
7
Page

Prof. Raju R. Vathari


UNIT-4

try and catch block

try block
 Inside try block we write the block of statements which causes executions at run time in
other words try block always contains problematic statements.
 The "try" keyword is used to specify a block where we should place exception code. The
try block must be followed by either catch or finally. It means, we can't use try block
alone.

Important points about try block

 If any exception occurs in try block then CPU controls comes out to the try block and
executes appropriate catch block.

 After executing appropriate catch block, even though we use run time statement, CPU
control never goes to try block to execute the rest of the statements.

 Each and every try block must be immediately followed by catch block that is no
intermediate statements are allowed between try and catch block.

Syntax

try
{
.....
}
catch()
{
....
}

 Each and every try block must contains at least one catch block. But it is highly
recommended to write multiple catch blocks for generating multiple user friendly error
messages.

 One try block can contains another try block that is nested or inner try block can be
8

possible.
Page

Prof. Raju R. Vathari


UNIT-4

Nested try block syntax:


Syntax

try
{
.......
try
{
.......
}
}

catch block
Inside catch block we write the block of statements which will generates user friendly
error messages.

The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.

catch block important points


 Catch block will execute exception occurs in try block.
 You can write multiple catch blocks for generating multiple user friendly error
messages to make your application strong. You can see below example.
 At a time only one catch block will execute out of multiple catch blocks.
Example without Exception Handling
Example

classExceptionDemo
{
publicstaticvoid main(String[] args)
{
int a=10, b=0;
b=a/0;
System.out.println("Denominator not be zero");
}
}

Abnormally terminate program and give a message like below, this error message is not
understandable by user so we convert this error message into user friendly error message,
9

like "denominator not be zero".


Page

Prof. Raju R. Vathari


UNIT-4

Example of Exception Handling


Example:
classExceptionDemo
{
public static void main(String[] args)
{
int a=10, b=0;
try
{
b=a/0;
}
catch (ArithmeticException e)
{
System.out.println("Denominator not be zero");
}
}
}

Output

Denominator not be zero

Multiple catch block

You can write multiple catch blocks for generating multiple user friendly error messages
to make your application strong. You can see below example.

A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.

Points to remember

o At a time only one exception occurs and at a time only one catch block is executed.
10

o All catch blocks must be ordered from most specific to most general, i.e. catch for
Page

ArithmeticException must come before catch for Exception.

Prof. Raju R. Vathari


UNIT-4

Syntax is:
try
{
//Exception code
}
catch(exception_name ref-var)
{
//Handling errors
}
catch(exception_name ref-var)
{
//Handling errors
}
---------------------------------------------------------
Example: 1
classExceptionDemo
{
public static void main(String[] args)
{
int a=10, b=0, div;
try
{
div=a/b;
System.out.println("Result: "+div);
}
catch(ArithmeticExceptionae)
{
System.out.println("Denominator not be zero");
}
catch(Exception e)
{
System.out.println("Enter valid number");
}
}
}

Output

Denominator not be zero


11
Page

Prof. Raju R. Vathari


UNIT-4

Example 2:
class MultipleCatchBlock2
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
System.out.println(a[10]);
}
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");
}
System.out.println("rest of the code");
}
}

OUTPUT:
ArrayIndexOutOfBounds Exception occurs

rest of the code


12
Page

Prof. Raju R. Vathari


UNIT-4

Example 3:
public class MultipleCatchBlock3
{
public static void main(String[] args)
{
try
{
String s=null;
System.out.println(s.length());
}
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");
}
System.out.println("rest of the code");
}
}

OUTPUT:
Parent Exception occurs

rest of the code


13
Page

Prof. Raju R. Vathari


UNIT-4

Example 4:
class MultipleCatchBlock4
{
public static void main(String args[])
{
try
{
int x=10/0;
}
catch(Exception e)
{
System.out.println("common task completed");
}

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


}
}

OUTPUT:
Common task completed
Rest of the code…..

Note:
catch(Exception e)
{
System.out.println("common task completed");
}

Here Exception is a root class for all exceptions. If any exception occur in try automatically
executed this above catch block.

That Exception root class contains all type of exceptions like;

1. ArithmeticException

2. ArrayIndexOutOfBoundException

3. FileNotFoundException
14
Page

Prof. Raju R. Vathari


UNIT-4

User-defined Custom Exception in Java


Java provides us facility to create our own exceptions which are basically derived classes
of Exception.
Throw keyword:-
 It is used to handover user created Exception object to JVM.
 It is used to throw exception explicitly.
 By using throw keyword it is possible throw predefined Exceptions & custom exception
but it is always recommended to throw custom exceptions.

Note: - throw keyword is used to handover user created exception object to JVM whether it is
predefined exception class or user defined exception class but it is always recommended
throw custom exception.

Example:- throw statement throw an predefined exception.

Step 1:- create the Exception object explicitly by the developer by using new keyword.
newInvalidAgeException("Shridhar not eligible");

Step 2:- handover (throw) user created Exception object to jvm by using throw keyword.
throw new InvalidAgeException ("Shridhar not eligible");

Example:-
importjava.util.*;
class Test
{
static void status(int age)
{
if (age<18)
{
throw new InvalidAgeException("not eligible for vote");
}
else
{
System.out.println("welcome to the voting");
}
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
int age=s.nextInt();
Test.status(age);
System.out.println("rest of the code");
}
}
15
Page

Prof. Raju R. Vathari


UNIT-4

OUTPUT:
Run 1: Run 2:
C:\Users\staff1\Desktop>javac Test.java C:\Users\staff1\Desktop>java Test
C:\Users\staff1\Desktop>java Test please enter your age
please enter your age 12
26 Exception in thread "main"
welcome to the voting java.lang.ArithmeticException: not eligible for vote
rest of the code at Test.validate(Test.java:8)
at Test.main(Test.java:19)

Example: - throw statement throw a user defined exception.


To achieve this mechanism first we must know how to create user defined exception
then we are able to use this throw keyword.

There are two types of exceptions present in the java language


1)Predefined Exceptions.
ArithmeticException, IOException, NullPointerException…………..etc

2)User defined Exceptions.(created by user)


InvalidAgeException, MyException…etc

Customization of exception handling :-( creation of predefined exceptions)

There are two types of user defined exceptions


1. User defined checked exception.
a. Default constructor approach.
b. Parameterized constructor approach.
2. User defined un-checked Exception.
a. Default constructor approach.
b. Parameterized constructor approach.

Creation of user defined checked Exception by using default constructor approach:-

Step-1:- create the user defined checked Exception


Normal java class will become Exception class whenever we are extends Exception
class.

InvaliedAgeException.java:-

public class InvalidAgeExcepiton extends Exception

//default constructor

}
16
Page

Prof. Raju R. Vathari


UNIT-4

Example to create user defined exception by using default constructor.


// A Class that represents user-defined exception using parameterized constructor.

importjava.util.Scanner;
classInvalidAgeException extends Exception
{
//Default Constructor.
}

// A Class that uses above MyException


public class Main
{
static void status(int age) throws InvalidAgeException
{
if(age>20)
{
System.out.println("Marry");
}
else
{
throw new InvalidAgeException();
}
}

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


{
Scanner scr=new Scanner(System.in);
System.out.println("Enter ur age");
int age=scr.nextInt();
Main.status(age);
}
}

OUTPUT:
Run 1: Run 2:
C:\Users\staff1\Documents>javac Test.java C:\Users\staff1\Documents>java Test
C:\Users\staff1\Documents>java Test Enter ur age
Enter ur age 15
23 Exception in thread "main" InvalidAgeException
Marry at Test.status(Test.java:19)
at Test.main(Test.java:28)
17
Page

Prof. Raju R. Vathari


UNIT-4

Example :-Creation of user defined checked exception by using parameterized constructor


approach.

step-1:- create the user defined checked exception class.


Normal java class will become checked exception class when we extend Exception
class.
InvalidAgeException.java
// A Class that represents user-defined exception using parameterized constructor.

importjava.util.Scanner;
classInvalidAgeException extends Exception
{
public InvalidAgeException(String s)
{
super(s); // Call constructor of parent Exception
}
}

// A Class that uses above InvalidAgeException


public class Main
{
static void status(int age) throws InvalidAgeException
{
if(age>20)
{
System.out.println("Marry");
}
else
{
throw new InvalidAgeException("U r not eligible for marry");
}
}
// Driver Program
public static void main(String args[]) throws InvalidAgeException
{
Scanner scr=new Scanner(System.in);
System.out.println("Enter ur age");
int age=scr.nextInt();
Main.status(age); //calling status() method using classname.
}
}
OUTPUT:
Run 1: Run 2:
C:\Users\staff1\Desktop>javac C:\Users\staff1\Desktop>java Main
Main.java Enter ur age
C:\Users\staff1\Desktop>java Main 18
Enter ur age Exception in thread "main" InvalidAgeException: U r not eligible for
23 marry
18

Marry at Main.status(Main.java:24)
at Main.main(Main.java:33)
Page

Prof. Raju R. Vathari


UNIT-4

Java Input Output: Java io package:


 Java.io package contains classes to perform input and output operations.
By using java.io package we are preforming file handling java.

Java IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java.
Stream:-
Stream is nothing but sequence of data, and it is called as stream means stream of water
continuous flow.
In general, a stream means continuous flow of data. Streams are clean way to deal with
input/output without having every part of your code understand the physical.

Stream is a communication channel between source and destination &A stream is a sequence of

data.

Input stream:-Program uses Input stream to read the data from a source one item at a time.
19
Page

Prof. Raju R. Vathari


UNIT-4

Some important Byte stream classes.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard
data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method

These classes define several key methods. Two most important are

1. read() : reads byte of data.


2. write() : Writes byte of data.

Java encapsulates Stream under java.io package. Java defines two types of streams.
They are,

1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.

Java Byte Stream Classes


Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.
20
Page

Prof. Raju R. Vathari


UNIT-4

While working with streams we will get two exceptions mainly FileNotFoundException
21

,IOException& these two exceptions are checked exceptions so must handle these exception
by using try-catch blocks or throws keyword.
Page

Prof. Raju R. Vathari


UNIT-4

Limitation of byte streams:-


It reads the data only one byte at a time hence it takes more time to copy.
Must close the streams always.
These streams always hitting hard disk to retrieve the data it reduces the performance

Character streams:-
Program uses character stream to perform input & output of character data. All
character stream classes developed based on Reader & Writer classes.
To demonstrate how the character stream works file I/O provided two main classes

FileReader
oIt is used to read the data from source one item at a time.
oTo read the data from source use read() method of FileInputStream class.
publicint read() throws java.io.IOException;
read() method returns first character Unicode value in the form of integer
value.

FileWriter
oIt is used to write the data to destination one item at a time.
oTo write the data to destination use write() method of FileOutputStream class.
public void write(intunicode) throws java.io.IOException;
write() method is taking Unicode value of the character as a parameter.

Example: CharacterStream
-----------------------------------------
Save As: CharacterStream
import java.io.*;
classCharacterStream
{
public static void main(String[] args) throws FileNotFoundException,IOException
{
FileReaderfr = new FileReader("abc.txt");
FileWriterfw = new FileWriter("xyz.txt");

int c;
while((c=fr.read())!=-1)
{
fw.write(c);
}
fr.close();
fw.close();
22

}
}
Page

Prof. Raju R. Vathari


UNIT-4

Note :
1. In CopyCharacters, the int variable holds a character value in its last 16 bits; in CopyBytes, the int
variable holds a byte value in its last 8 bits. CopyCharacters is very similar to CopyBytes.
2. The most important difference is that CopyCharacters uses FileReader and FileWriter for input
and output in place of FileInputStream and FileOutputStream.
3. Notice that both CopyBytes and CopyCharacters use an int variable to read to and write from.
However, in CopyCharacters, the int variable holds a character value in its last 16 bits; in
CopyBytes, the int variable holds a byte value in its last 8 bits.

Line oriented I/O:-


In above two streams(byte & character) it is possible to read only one item at time it
increases number of read & write operations hence the performance is decreased.

To overcome above limitation to improve performance of the application instead of


reading the data item by item, read the data line-by-line format to improve the performance.

To perform line oriented operations use two classes.

BufferedReader
oIt is used to read the data from source file in line by line format.
oTo read the data use readLine() method of BufferedReader class .
publicjava.lang.StringreadLine() throws java.io.IOException;
The readLine() method returns first line of the text file in the form of String.

PrintWriter
oIt is used to write the data to destination file in line by line format.
oTo write the data to file use println() method of PrintWriter class.
public void println(java.lang.String);
The above method used to write the data to destination file.

Buffered Streams:-
 In previous examples we are using un-buffered I/O .This means each read and write request
is handled directly by the underlying OS.
In normal streams each request directly triggers disk access it is relatively expensive &
performance is degraded.

To overcome above limitations use buffered streams.


Bufferd input stream read the data from buffered memory and it interacting with hard
diskonly when buffered memory is empty.
Buffered output stream write the data to buffer memory.
23
Page

Prof. Raju R. Vathari


UNIT-4

There are four buffered stream classes.


Buffered byte streams,
1. BufferedInputStream
2. BufferedOutputStream
A program can convert an un buffered stream into buffered streams.
newBufferedInputStream(new FileInputStream("abc.txt"));
newBufferedOutputStream(new FileOutputSream("xyz.txt"));

Buffered Character streams,


3. BufferedReader
4. BufferedWriter
A program can convert an un buffered stream into buffered streams.
newBufferedReader(new FileReader("abc.txt"));
newBufferedWriter(new FileWriter("xyz.txt"));

Example for Buffered Character streams,


--------------------------------------------------
import java.io.*;
public class BufferedIOStream
{
public static void main(String[] args) throws IOException,FileNotFoundException
{
BufferedInputStream br = new BufferedInputStream(new FileInputStream("abc.txt"));
BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream("xyz.txt"));
int Line;
while ((Line = br.read()) != -1)
{
//Process each line and add output to xyz.txt file
bw.write(Line);
}
br.close();
bw.close();
}
}
24
Page

Example for Buffered Bytes streams,

Prof. Raju R. Vathari


UNIT-4

--------------------------------------------------
import java.io.*;
public class Main123
{
public static void main(String[] args) throws FileNotFoundException,IOException
{
BufferedReaderbr = new BufferedReader(new FileReader("abc.txt"));
BufferedWriterbw = new BufferedWriter(new FileWriter("xyz.txt"));

String Line = null;


while ((Line = br.readLine()) != null)
{
//Process each line and add output to xyz.txt file
bw.write(Line);
bw.newLine();
}
// do not forget to close the buffer reader
br.close();
// close buffer writer
bw.close();
}
}

PrintWriter
oIt is used to write the data to destination file in line by line format.
oTo write the data to file use println() method of PrintWriter class.
public void println(java.lang.String);
The above method used to write the data to destination file.
25

Multithreading in java
Page

Prof. Raju R. Vathari


UNIT-4

Thread:

o A thread is a light-weight smallest part of a process that can run concurrently with the
other parts (other threads) of the same process.
o Threads are independent because they all have separate path of execution that’s the
reason if an exception occurs in one thread, it doesn’t affect the execution of other
threads.
o All threads of a process share the common memory.

Multithreading:

The process of executing multiple threads simultaneously is known as


multithreading.

Example:

Advantages of Java Multithreading:

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a
single thread.
26
Page

Prof. Raju R. Vathari


UNIT-4

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use


multitasking to utilize the CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)

o Each process has an address in memory. In other words, each process allocates a
separate memory area.
o A process is heavyweight.
o Cost of communication between the processes is high.

2) Thread-based Multitasking (Multithreading)

o Threads share the same address space (Memory).


o A thread is lightweight.
o Cost of communication between the thread is low.

What is Thread in java?

 A thread is a lightweight sub-process, the smallest unit of processing. It is a separate


path of execution.
 Threads are independent. If there is occurs exception in one thread, it doesn't affect
other threads. It uses a shared memory area.

As shown in the side figure, a thread is


executed inside the process. There is
context-switching between the threads.
There can be multiple processes inside the
OS, and one process can have multiple
threads.
27
Page

Prof. Raju R. Vathari


UNIT-4

Difference between Multithreading and Multitasking

Multithreading Multitasking

It is a programming concept in which a It is operating system concept in


program or process is divided into two or which multiple tasks are performed
more subprograms or threads that are simultaneously.
executed at the same time in parallel.

It supports execution of multiple parts of It supports execution of multiple


single program simultaneously. programs simultaneously.

It is highly efficient. It is less efficient.

A thread is smallest unit of programming. A program or process is the


smallest unit a multitasking
environment.

Java Thread class:

Java provides Thread class to achieve thread programming. Thread class provides
constructors and methods to create and perform operations on a thread. Thread class extends
Object class and implements Runnable interface.

Java Thread Methods: (Some important thread methods…)

These below methods help to create the threads.

start() It is used to start the execution of the thread.

run() It is used to do an action for a thread.

sleep() It sleeps a thread for the specified amount of time.

currentThread() It returns a reference to the currently executing thread


object.
getPriority() It returns the priority of the thread.

setPriority() It changes the priority of the thread.

isAlive() It tests if the thread is alive.

getName() It returns the name of the thread.

setName() It changes the name of the thread.


28
Page

Prof. Raju R. Vathari


UNIT-4

Main Thread:

When a Java program starts up, one thread begins running immediately. This is
usually called the main thread of our program, because it is the one that is executed when our
program begins.

Properties:
 It is the thread from which other “child” threads will be started.

 Often, it must be the last thread to finish execution because it performs various
shutdown actions

The main thread is created automatically when our program is started. To control it we must
obtain a reference to it. This can be done by calling the method currentThread( ) which is
present in Thread class. This method returns a reference to the thread on which it is called.
The default priority of Main thread is 5 and for all remaining user threads priority will be
inherited from parent to child.

// Java program to control the Main Thread


class MyThread extends Thread
{
public static void main(String[] args)
{
// getting reference to Main thread
Thread t = Thread.currentThread();

// getting name of Main thread


System.out.println("Current thread: " + t.getName());

// changing the name of Main thread


t.setName("Raju");
System.out.println("After name change: " + t.getName());

// getting priority of Main thread


System.out.println("Main thread priority: "+ t.getPriority());
}
}
-----------------------------------------------------------------------------
C:\Users\student\Desktop>java MyThread.java
C:\Users\student\Desktop>java MyThread
Current thread: main
After name change: Raju
29

Main thread priority: 5


Page

Prof. Raju R. Vathari


UNIT-4

Creating Threads:

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

1. By extending Thread class:

We can make our class runnable as thread by extending the class java.lang.Thread.
This gives us access to all the methods directly. It includes the following steps:

1) Declare the class as extending the Thread class.


2) Implement the run() method that is responsible for executing the sequence of code
that the Thread will execute.
3) Create a thread object and call start() method to initiate the thread execution.
1) Declaring the class :
The Thread class can be extended as follows:
class MyThread extends Thread
{
……………
……………
}

Now we have a new type of thread MyThread.

2) Implementing the run() method:

The run() method has been inherited by Thread class. We have to override this method in
order to implement the code to be executed by our thread.
Syntax:
run( )
{
…………… //Thread code here.
……………
}

When we start the new thread , Java calls the start method’s run() method, so it is the run()
where the all action takes place.
30
Page

Prof. Raju R. Vathari


UNIT-4

3) Starting New Thread:


To actually create and run instance of our thread class, we must write the following.

MyThread t=new MyThread( );


t.start( );

 The above first line creates the object for the MyThread class. The thread will run
this object is not yet running. The thread is in a newborn state.

 The second line calls the start() method to move into the runnable state. Then
the java runtime will schedule (Thread Schedule) the thread to run by invoking
its run() method. Now, the thread is said to be in the running state.

An Example of using the Thread class:

class MyThread extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
}
class Test
{
public static void main(String args[ ])
{
MyThread t1=new MyThread();
t1.start();
}
}

OUTPUT
----------------
thread is running...
31
Page

Prof. Raju R. Vathari


UNIT-4

Java Runnable Interface


Java runnable is an interface used to execute code on a concurrent thread. It is an interface
which is implemented by any class if we want that the instances of that class should be
executed by a thread.

The runnable interface has an undefined method run( ) with void as return type, and it takes
in no arguments. The method summary of the run( ) method is given below-

Method Description

public void run( ) This method takes in no arguments. When the object of a class
implementing Runnable class is used to create a thread, then the run
method is invoked in the thread which executes separately.

The Runnable interface provides a standard set of rules for the instances of classes
which wish to execute code when they are active. The most common use case of the
Runnable interface is when we want only to override the run method. When a thread is
started by the object of any class which is implementing Runnable, then it invokes the run
method in the separately executing thread.

The Runnable interface declares the run( ) method that is required for implementation
thread in our programs. To do this, we must perform the steps listed below:

1. Declare the class as implementing the Runnable interface.


2. Implement the run( ) method.
3. Create a thread by defining an object that is instantiated form this “runnable”
class as the target the thread.
4. Call the threads start( ) method to run the thread.

Implementing Runnable
It is the easiest way to create a thread by implementing Runnable. One can create a thread on
any object by implementing Runnable. To implement a Runnable, one has only to implement
the run method.

public void run()


32

In this method, we have the code which we want to execute on a concurrent thread. In this
Page

method, we can use variables, instantiate classes, and perform an action like the same way the

Prof. Raju R. Vathari


UNIT-4

main thread does. The thread remains until the return of this method. The run method
establishes an entry point to a new thread.

How to create a thread using Runnable interface


To create a thread using runnable, use the following code-

MyThread t1 = new MyThread();

Thread thread = new Thread(t1);


thread.start();

The thread will execute the code which is mentioned in the run() method of the
Runnable object passed in its argument.

A simple thread example using runnable


class MyThread implements Runnable
{
public void run()
{
System.out.println("Hi i am user thread..");
}

public static void main(String[] args)


{
MyThread ex = new MyThreads();
Thread t1= new Thread(ex);
t1.start();
System.out.println("Main Thread");
}
}
Output:
Hi I am user thread
Main Thread.
33
Page

Prof. Raju R. Vathari


UNIT-4

Different Threads are performing different tasks:


-----------------------------------------------------------------
1) Particular task is performed by the number of threads here number of threads(t1,t2,t3)
are executing same method (functionality).
2) In the above scenario for each and every thread one stack is created. Each and every
method called by particular Thread the every entry stored in the particular thread stack.

class MyThread1 extends Thread


{
public void run()
{
System.out.println("Raju’s task");
}
}
class MyThread2 extends Thread
{
public void run()
{
System.out.println("Ravi’s task");
}
}
class MyThread3 extends Thread
{
public void run()
{
System.out.println("Anil’s task");
}
}
class ThreadDemo
{
public static void main(String[] args) //1- main Thread
{
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
MyThread3 t3 = new MyThread3();
t1.start(); //2
t2.start(); //3
t3.start(); //4
}
34

}
Page

Prof. Raju R. Vathari


UNIT-4

Output:
Raju’s task
Ravi’s task
Anil’s task

Multiple threads are performing single task:


-------------------------------------------------------------
class MyThread extends Thread
{
public void run()
{
System.out.println("JavaThread’s task is running…..");
}
}
class ThreadDemo
{
public static void main(String[] args)//main Thread is started
{
MyThread t1=new MyThread(); //new Thread created
MyThread t2=new MyThread(); //new Thread created
MyThread t3=new MyThread(); //new Thread created
t1.start(); //Thread started
t2.start(); //Thread started
t3.start(); //Thread started
}
}

Output
JavaThread’s task is running…..
JavaThread’s task is running…..
JavaThread’s task is running…..
35
Page

Prof. Raju R. Vathari


UNIT-4

Thread Priorities:-
1. Every Thread in java has some property. It may be default priority provided be the JVM or
customized priority provided by the programmer.
2. The valid range of thread priorities is 1 – 10. Where 1 is lowest priority and 10 is highest
priority.
3. The default priority of main thread is 5. The priority of child thread is inherited from the
parent.
4. Thread defines the following constants to represent some standard priorities.
5. Thread Scheduler will use priorities while allocating processor the thread which is having
highest priority will get chance first and the thread which is having low priority.
6. If two threads having the same priority then we can’t expect exact execution order it
depends upon Thread Scheduler.
7. The thread which is having low priority has to wait until completion of high priority
threads.
8. Three constant values for the thread priority.
a) MIN_PRIORITY = 1
b) NORM_PRIORITY = 5
c) MAX_PRIORITY = 10
Thread class defines the following methods to get and set priority of a Thread.
Public final int getPriority()
Public final void setPriority(int priority)

Here ‘priority’ indicates a number which is in the allowed range of 1 – 10. Otherwise we
will get Runtime exception saying “IllegalArgumentException”.

Java program to print the name of current thread and priority and set the
priority by user.

class MyThread extends Thread


{
public void run()
{
System.out.println("current Thread name = "+Thread.currentThread().getName());
System.out.println("current Thread priority = "+Thread.currentThread().getPriority());
}
}
class ThreadDemo
{
36

public static void main(String[] args)//main thread started


{
Page

MyThread t1 = new MyThread();

Prof. Raju R. Vathari


UNIT-4

MyThread t2 = new MyThread();


t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}

Output:

C:\Users\staff1\Desktop>java ThreadDemo
current Thread name = Thread-0
current Thread name = Thread-1
current Thread priority = 10
current Thread priority = 1
37
Page

Prof. Raju R. Vathari


UNIT-4

13. Illustrate creation of thread by


a) Extending Thread class. b) Implementing Runnable interface

import java.io.*;
class Thread1 extends Thread
{
public void run()
{
System.out.println("Thread is running...");
}
}
class Thread2 implements Runnable
{
public void run()
{
System.out.println("Runnable is running...");
}
}
class Lab13
{
public static void main(String args[])
{
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();

Thread t3=new Thread(t1);


Thread t4=new Thread(t2);

t3.start();
t4.start();
}
}
Output:
-------------------------------------
Thread is running…
Runnable is running…
38
Page

Prof. Raju R. Vathari


UNIT-4

14. Write a Java program that creates three threads. First thread displays
“Good Morning” every one second, the second thread displays “Hello”
every two seconds and the third thread displays “Welcome” every three
seconds.

import java.lang.*;
class ThreadOne extends Thread
{
public void run()
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("Good morning");
}
}

class ThreadTwo extends Thread


{
public void run()
{
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
System.out.println(e);
}

System.out.println("Hello");
}
}
39
Page

Prof. Raju R. Vathari


UNIT-4

class ThreadThree extends Thread


{
public void run()
{
try
{
Thread.sleep(3000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("Welcome");
}
}

class Lab14 extends Thread


{
public static void main(String args[])
{
ThreadOne t1=new ThreadOne();
ThreadTwo t2=new ThreadTwo();
ThreadThree t3=new ThreadThree();

t1.start();
t2.start();
t3.start();
}
}

Output:
Good Morning.
Hello.
Welcome.
40
Page

Prof. Raju R. Vathari


UNIT-4

Using isAlive( ) and join( )

Sometimes one thread needs to know when other thread is terminating. In


java, isAlive() and join() are two different methods that are used to check whether a thread
has finished its execution or not.

The isAlive() method returns true if the thread upon which it is called is still running
otherwise it returns false.

final boolean isAlive()

But, join() method is used more commonly than isAlive(). This method waits until the thread
on which it is called terminates.

final void join() throws InterruptedException

Using join() method, we tell our thread to wait until the specified thread completes its
execution. There are overloaded versions of join() method, which allows us to specify time
for which you want to wait for the specified thread to terminate.

final void join(long milliseconds) throws InterruptedException

Java isAlive ( ) method

Example and how the isAlive() method works.

public class MyThread extends Thread


{
public void run()
{
System.out.println("r1 ");
try
{
Thread.sleep(500);
41

}
Page

Prof. Raju R. Vathari


UNIT-4

catch(InterruptedException ie)
{
// do something
}
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
----------------------------------------------------------------------------------
OUTPUT:
E:\RajuVathari\THIRD SEMESTER\LAB PROGRAMS>java MyThread
t1 thread is alive :true
t2 thread is alive :true
Child thread is running...
Child thread is running...
I am child thread...!!!
I am child thread...!!!
42
Page

Prof. Raju R. Vathari


UNIT-4

Example of thread without join() method

public class MyThread extends Thread


{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie){ }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
}
}

Output:
--------------------------------

r1

r1

r2

r2
43
Page

Prof. Raju R. Vathari

Das könnte Ihnen auch gefallen