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

Java Unit-Iii

Uploaded by

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

Java Unit-Iii

Uploaded by

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

JAVA PROGRAMMING

UNIT-3

Exception Handling- Fundamentals of exception handling, Exception types,


Termination or resumptive models, Uncaught exceptions, using try and
catch, multiple catch clauses, nested try statements, throw, throws and
finally, built- in exceptions, creating own exception sub classes.

Multithreading- Differences between thread-based multitasking and


process-based multitasking, Java thread model, creating threads, thread
priorities, synchronizing threads, inter thread communication.

A software Engineer may also commit several errors while designing the
project or developing the code. These errors are also called bugs and the
process of removing them is called “debugging”.

Errors in Java Program:


Basically there are three types of errors in java program:
 Compile-Time Errors
 Runtime Errors
 Logical Errors

Compile-time errors:
The Compile-Time Errors are syntactical errors in the code, due to
which the program fails to compile. Let us consider the following java
program in which the compiler gives an error.

import java.lang.*;
class D
{
public static void main(String args[])
{
int a=0,b=9;
System.out.println(a+"\t"+b);
System.out.println("Hello ");
System.out.println();
}
}

Logical Errors:

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

The logical errors depict the flaws in the logic of the program. The
programmer might be using a wrong formula or the design of the program
itself is wrong. Logical errors are not detected either by Java compiler or
JVM. Let us consider the following program in which instead of addition
subtraction operation is performed.

import java.lang.*;
class Demo
{
public static void main(String args[])
{
int a=10,b=9;
System.out.println("sum of two numbers :"+(a-b));
}
}

Runtime Error:
The error that occurs at the execution time is called Runtime Error.

import java.lang.*;
class D
{
public static void main()
{
int a=0,b=9; System.out.println(a+"\t"+b);
System.out.println("Sum of Two Numbers : "+(a+b));
}
}

Exception:
An Exception is a Runtime Error. An Exception is an abnormal and
unexcepted and also unwanted event that disturbs the normal flow of the
program. All Exceptions occur only at runtime but some exceptions are
detected at compile time and some others at runtime. The exceptions that
are checked at compilation time by the java compiler are called checked

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

exceptions while the exceptions that are checked by the JVM are called
unchecked exception.

Ex: FileNotFoundException
ArithmeticException

Exception occurs in situation like


 The File you try to open may not exist.
 The class file you want to load may be missing or in the wrong format.
 The other end of the network connection may not existing.
 Dividing a number by zero.
 Accessing the index of the array out of is range

As a good programming practice we are responsible for handling the


exceptions for graceful termination of the program

class Demo
{
public static void main(String[] args)
{
int a=10,b=0,c;
System.out.println("hello");
c=a/b;
System.out.println(c);
System.out.println("Hello World!");
}
}

Types of Exceptions:
They are two types of Exceptions available in java
1. Built-in-Exception
2. User-defined Exception

Built-in-Exception:
Built-in-Exceptions are which already available in java. These Exceptions
are suitable to explain certain error situations.

There are mainly two types of built-in exceptions:


 Checked Exception
 Unchecked Exception

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

Here, an error is considered as the unchecked exception.

Checked Exception:
The classes which directly inherit Throwable class except both
RuntimeException and Error are known as checked exceptions

Ex: IOException,
SQLException

Checked exceptions are checked at compile-time.

Unchecked Exception:
The classes which inherit RuntimeException are known as unchecked
exceptions

Ex: ArithmeticException,
NullPointerException,
ArrayIndexOutOfBoundsException.

Unchecked exceptions are not checked at compile-time, but they are


checked at runtime.

Error:
Error is irrecoverable

Ex: OutOfMemoryError
VirtualMachineError
AssertionError

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

Exception models:

In java, there are two exception models. Java programming language


has two models of exception handling. The exception models that java
suports are as follows.

 Termination Model

 Resumptive Model

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

Termination Model:

In the termination model, when a method encounters an exception, further


processing in that method is terminated and control is transferred to the
nearest catch block that can handle the type of exception encountered.

In other words we can say that in termination model the error is so critical
there is no way to get back to where the exception occurred.

Resumptive Model:

The alternative of termination model is resumptive model. In resumptive


model, the exception handler is expected to do something to stable the
situation, and then the faulting method is retried. In resumptive model we
hope to continue the execution after the exception is handled.

In resumptive model we may use a method call that want resumption like
behavior. We may also place the try block in a while loop that keeps re-
entering the try block until the result is satisfactory.

Uncaught Exceptions:

In java, assume that, if we do not handle the exceptions in a program. In


this case, when an exception occurs in a particular function, then Java
prints a exception message with the help of uncaught exception handler.

The uncaught exceptions are the exceptions that are not caught by the
compiler but automatically caught and handled by the Java built-in
exception handler.

Java programming language has a very strong exception handling


mechanism. It allow us to handle the exception use the keywords like try,
catch, finally, throw, and throws.

When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the
exception occurs and terminates the thread.

import java.lang.*;
class Demo
{
public static void main(String[] args)
{
int a=10,b=0,c;
System.out.println("hello");

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

c=a/b;
System.out.println(c);
System.out.println("Hello World!");
}
}

Exception Handling Mechanism:

Exceptions are the conditions that occur at runtime and may cause
the termination of program. But they are recoverable using Exception
Handling Mechanism. Exceptions can be handled by using five keywords.

 The "try" keyword is used to specify a block where we should


trouble making statements.
Try
 The try block must be followed by either catch or finally.
 It means, we can't use try block alone.
 The "catch" block is used to handle the exception occurred in
try block.
catch  It must be preceded by try block which means we can't use
catch block alone.
 It can be followed by finally block later.
 The "finally" block is used to execute the important code of the
finally program.
 It is executed whether an exception is handled or not.

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

 The "throws" keyword is used to declare exceptions.


 It doesn't throw an exception.
throws  It specifies that there may occur an exception in the method.
 It is always used with method signature.

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

try:
Identify the statements that may trouble at runtime and place them in
the try block

catch:
When the try block throws the exception the catch block handles the
exception. If the try block does not throw the exception the catch block is
simply ignored.

try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
// Handles Exception raised in Try Block
}

We must provide a suitable exception handler that can handle the


exception thrown by the try block successfully

import java.lang.*;
class Demo
{
public static void main(String[] args)
{
int a=10,b=0,c;
System.out.println("hello");
c=a/b;
System.out.println(c);
System.out.println("Hello World!");
}
}

In the above program the successful exception handler is arithmetic


exception for the problem of “division by zero”.
One of the ways of handling the exception is using try and catch
blocks. Let us consider the following program:

class Demo1

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

{
public static void main(String[] args)
{
int a=100,b=0,c; System.out.println("hello1 ");
try
{
c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(" Do Not Divide by Zero "+e);
}
System.out.println("hello1");
System.out.println("Hello2");
}
}

ArrayIndexOutOfBoundsException: This exception raises when we are


trying to access the array the element out of its range.

import java.lang.*;
class Demo1
{
public static void main(String args[])
{
int x[]={10,20,30};
System.out.println("hello1");
try
{
System.out.println(x[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
System.out.println("hello2");

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

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

StringOutOfBoundsException: This exception raises when we are trying to


access the character out of its range.

class Demo2
{
public static void main(String args[])
{
String s="abc";
try
{
System.out.println(s.charAt(3));
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println("Access out of its range");
}
}
}

NumberFormatException: Thrown to indicate that the application has


attempted to convert a string to one of the numeric types, but that the string
does not have the appropriate format.

import java.lang.*;
class NumberF
{
public static void main(String args[])
{
try

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

{
int a = Integer.parseInt(args[0]);
System.out.println("FIRST ARGUMENT "+a);
int b = Integer.parseInt(args[1]);
System.out.println("second ARGUMENT "+b);
int c = Integer.parseInt(args[2]);
System.out.println(a+"\t"+b+"\t"+c);
}
catch(NumberFormatException e)
{
System.out.println("unable to convert from string to int ");
}
}
}

In the above program we are passing three argument to the main method as
Strings out of which two arguments we can convert into integer but third
argument cannot converted from string to int so for third argument
NumberFormatException raised.

NullPointerException: Thrown when an application attempts to use null in


a case where an object is required. It is a unchecked exception. This
exception occurs in the following situations:
 Calling the instance method on a null object.
 Accessing or modifying the field of a null object
 Taking the length of null as if it were an array.

class Demo4
{
public static void main(String args[])
{
String s1=null;
try
{
System.out.println(s1.length());
}
catch(NullPointerException e)

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

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

NegativeArraySizeException:Thrown if an application tries to create an


array with negative size.

class Demo5
{
public static void main(String args[])
{
try
{
int x[]= new int[-7];
}
catch(NegativeArraySizeException e)
{
System.out.println(e);
}
}
}

Multiple catch Clauses:

Consider the following program in which ArithmeticException and


ArrayIndexOutOfBoundsException raised and handled only one Exception
i.e.,ArrayIndexOutOfBoundsException.

class Demo1
{
public static void main(String[] args)
{
int a=100,b=0,c; int s[]={10,30,40};
System.out.println("hello1 "); try
{
c=a/b; System.out.println(c); System.out.println(s[5]);
}
catch(ArrayIndexOutOfBoundsException e)
{

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

System.out.println(e);
}
System.out.println("hello1"); System.out.println("Hello2");
}
}

In the above program there is only one catch block for


ArrayIndexOutBoundsException but inside try block the first exception that
we are getting is ArithmeticException so there is no suitable handler for
ArithmeticException then the program terminates abnormally.

This situation can be handled by using multiple catch blocks.

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.
 At a time only one exception occurs and at a time only one catch block
is executed.
 All catch blocks must be ordered from most specific to most general,
i.e. catch for ArithmeticException must come before catch for
Exception.
try
{
---
}
catch(ArithmeticException ae)
{
---
}
catch(Exception e)
{
---
}

class Demo1
{
public static void main(String[] args)
{

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

int a=100,b=0,c;
int s[]={10,30,40};
System.out.println("hello1 ");
try
{
c=a/b;
System.out.println(c);
System.out.println(s[5]);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("hello1");
System.out.println("Hello2");
}
}

In the above program there are two catch block one is


ArithmeticExceptoin and other is ArrayIndexOutBoundsException the
program terminates gracefully.

Nested try block:

The try block within a try block is known as nested try block in java.

try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

catch(Exception e)
{
}
}
catch(Exception e)
{

class Demo
{
public static void main(String args[])
{
int a=10,b=0,c;
String s;
try
{
try
{
s=null;
//trying to print the character at index 0 of the string s
System.out.println(s.charAt(0));
}
catch(NullPointerException np)
{
System.out.println(np);
}
c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("Exception are Handled");
}
}

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

import java.io.*;
class Demo1
{
public static void main(String args[])throws IOException
{
try
{
try
{ //nested try block1
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception is Raised");
}

try
{ //nested try block2
int a[]=new int[5]; //index range : 0 to 4
a[5]=4;// trying to assigned array value at index 5
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}

BufferedReader br = new BufferedReader(new InputStreamReader


(System.in));
System.out.print("Enter an integer : ");
int n=Integer.parseInt(br.readLine());
System.out.println("other statement");
}
catch(Exception e)

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

{
System.out.println("Exceptions are handeled");
}
System.out.println("normal flow..");
}
}

Finally block:
In order to perform clean up operations like closing files and
terminating of threads the programmer has to write that particular code in
the finally block.

try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
// Handles Exception raised in Try Block
}
finally
{
// executes before try block ends
}
The statements inside the finally block are executed irrespective of whether
there is an exception or not. This ensures that all the opened files are
properly closed and all running threads are properly terminated.

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

class Demo1
{
public static void main(String[] args)
{
int a=100,b=0,c;
int s[]={10,30,40};
System.out.println("hello1 ");
try
{
c=a/b;
System.out.println(c);
System.out.println(s[5]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
finally
{
System.out.println("Closing of files");
}
System.out.println("hello1");
System.out.println("Hello2");
}
}

Let us consider the following program in which both exceptions are raised
and handled with catch blocks.

class Demo1
{
public static void main(String[] args)
{
int a=100,b=0,c;
int s[]={10,30,40};
System.out.println("hello1 ");
try
{
c=a/b;

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

System.out.println(c);
System.out.println(s[5]);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
finally
{
System.out.println("Closing of files");
}
System.out.println("hello1");
System.out.println("Hello2");
}
}

Throws:
Even if the programmer is not handling the runtime exceptions, the
java compiler will not give any error related to runtime exceptions. But the
rule is that the programmer should handle checked exceptions. In case the
programmer does not want to handle the exceptions, he should throw them
out using throws clause. throws is keyword in java.

We can declare the exceptions in the method declarations, the


exceptions that occurs inside the method. If the method is not handling the
exception we can declare the exception by using throws keyword.

Using the throws keyword we can delegate the responsibility of


handling the exception to the caller of the method.

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

import java.lang.*;
import java.io.*;
class Demo1
{
public static void main(String[] args)
{
int a,b;
BufferedReader br = new BufferedReader(new InputStreamReader
(System.in));
System.out.println("Enter Integer ");
a=Integer.parseInt(br.readLine());
System.out.println("Enter another Integer");
b=Integer.parseInt(br.readLine());
System.out.println("sum of two numbers : "+(a+b));
System.out.println("Division of two numbers : "+(a/b));
}
}

The above program will not compile since there is a possibility that
readLine() raises an IOException which is a checked exception.

A checked exception must be caught by using try, catch or it must be


declared by using throws keyword.

import java.lang.*;
import java.io.*;
class Demo1
{
public static void main(String[] args)
{
int a,b;

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

try
{
BufferedReader br = new BufferedReader(new InputStreamReader
(System.in));
System.out.println("Enter Integer ");
a=Integer.parseInt(br.readLine());
System.out.println("Enter another Integer");
b=Integer.parseInt(br.readLine());
System.out.println("sum of two numbers : "+(a+b));
System.out.println("Division of two numbers : "+(a/b));
}
catch(IOException e)
{
System.out.println(e);
}
}
}

In the above program the exception is handled by using try, catch keywords.

import java.lang.*;
import java.io.*;
class Demo1
{
public static void main(String[] args)throws IOException
{
int a,b;
BufferedReader br = new BufferedReader(new InputStreamReader
(System.in));
System.out.println("Enter Integer ");
a=Integer.parseInt(br.readLine());
System.out.println("Enter another Integer");

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

b=Integer.parseInt(br.readLine());
System.out.println("sum of two numbers : "+(a+b));
System.out.println("Division of two numbers : "+(a/b));
}
}

In the above program the exception is not handled by using try and catch
but the exception is throw out of the method by using throws keyword.

import java.lang.*;
import java.io.*;
class Demo1
{
int a,b; // instace variable
public void accept()throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader
(System.in));
System.out.println("Enter Integer ");
a=Integer.parseInt(br.readLine());
System.out.println("Enter another Integer");
b=Integer.parseInt(br.readLine());
}
public void display()
{
System.out.println(a+"\t"+b);
}
public static void main(String[] args)throws IOException
{
Demo1 d = new Demo1();
d.accept();
d.display();
}
}

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

throw:
throw is keyword in java used to throw an exception explicitly and
catch it. Throw must be used only inside the try block otherwise compiler
gives an error.

class Sample
{
static void demo()
{
try
{
System.out.println("Inside Demo");
throw new NullPointerException("Throw Demo");
}
catch(NullPointerException ne)
{
System.out.println(ne);
}
}
}
class ThrowDemo
{
public static void main(String args[])
{
Sample.demo();
}
}

User defined Exception:


Sometimes, the built-in-exception in java are not able to handle
certain situtation.In such cases just like built-in-exceptions, the user can
also create his own exceptions which are called user-defined Exception.
Ex: InsufficientFundsExceptions
TooYoungException
TooOldException
NoTalentException

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

The following steps are followed in creation of user-defined exception

1. Create an exception class as a subclass of Exception class.


class MyException extends Exception

2. Take one parameter constructor that takes the string as the arugument
and call super class constructor.

3. Throw the exception by using throw keyword.

import java.io.*;
class NoMoneyException extends Exception
{
public NoMoneyException(String msg)
{
super(msg);
}
}
class Demo7
{
public static void main(String args[])throws IOException
{
int bal=15000,withdraw;
BufferedReader br = new BufferedReader(new InputStreamReader
(System.in));
System.out.println("Welcome to XXX Bank Services");
System.out.println("Enter Amount");
withdraw=Integer.parseInt(br.readLine());
try
{
if(bal<withdraw)
{
throw new NoMoneyException("sorry unable to process");
}
else
{
System.out.println("Please Wait U r Transaction being processing ");
}
}
catch(NoMoneyException e)
{
System.out.println(e);
}
System.out.println("Welcome to XXX Bank Services");

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

}
}

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

Multithreading

Thread:
A thread represents a separate path of execution of a group of
statements. In java if we write a group of statements, then these statements
are executed by jvm one-by-one. This means that in every java program
there is always a thread running internally.

A thread represents execution of statements. The way the statements


are executed is of two types:
 Single tasking
 Multi tasking

Single Tasking: A task means doing some calculations, processing etc. A


task involves execution of a group of statements. In single tasking
environment only one task is given to the processor at a time. In single
tasking a lot of processor time is wasted and processor has to sit idle
without any job for a long time.

Multi Tasking: To use processor’s time in an optimum way, we can give


several jobs at a time. This is called Multi Tasking. The main advantage of
multitasking is to use processor time in optimum way. By this way we can
complete several tasks at a time and thus achieve good performance.

Multitasking is of two types

 Process-based Multitasking
 Thread-based Multitasking

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

In Process-based Multitasking several programs are executed at a time by


the processor

In thread-based Multitasking several parts of a same program is executed at


a time by the processor.

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

Uses of Threads:
Threads can be used for multiple purpose. Some of the uses of threads
are:
 In server-side programs to serve the needs of multiple clients on a
network or internet.
 To create games and animation. Animation means moving the objects
from one place to another.

Multithreading:
Multithreading refers to two or more tasks executing concurrently
within a single program. A java process can be divided into a number of
threads and each thread can be given a different task.

Creating a Thread:
We know that in every java program, there is a main thread available
already. Apart from this main thread, we can also create our own threads in
a program.

There are two ways to create a thread in Java:


1. By Implementing the Runnable interface(java.lang.Runnable)
2. By Extending Thread class(java.lang.Thread)

Creating a thread by extending Thread class:

class TDemo extends Thread


{
public void run()
{
int i;
for(i=0;i<10;i++)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
}
}
public static void main(String args[])
{

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

TDemo d = new TDemo();


d.start();
}
}

sleep():
sleep() is a static method of Thread class which makes a running
thread to become inactive for the specified time in milli seconds passed as a
parameter.When the sleep() time is over the thread implicitly becomes active.

The signature of sleep() method is


public static void sleep(long milliseconds) throws InterruptedException

It throws a checked exception InterruptedException so we need to


catch the exception by placing it in try, catch.

Creating thread by using Runnable interface

class TDemo1 implements Runnable


{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
}
}

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

public static void main(String args[])


{
TDemo1 t=new TDemo1();
Thread t1=new Thread(t);
t1.start();
}
}

Single tasking using a Thread:


A thread can be employed to execute one task at a time. Suppose
there are three task to be executed. We can create a thread and pass the
three tasks one by one to the thread. For this purpose, we can write all
these tasks separately separate methods: task1(), task2(), task3(). Then
these methods should be called from run() method one by one.

Note: A thread executes only the code inside the main() method. It never
execute other methods unless they are called from run().

public class SingleTasking extends Thread


{
public void run()
{
task1();
task2();
task3();
}
public void task1()
{
System.out.println("task1");
}
public void task2()
{
System.out.println("task2");
}

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

public void task3()


{
System.out.println("Task3");
}
public static void main(String args[])
{
SingleTasking st=new SingleTasking();
st.start();
}
}

Muti Tasking using Threads:


In multi tasking, several tasks are executed at a time. For this
purpose, we need more than one thread. For example, to perform two tasks,
we can take two threads and attach them to the two tasks. Then those tasks
are simultaneously executed by the two threads. Using more than one
thread is called “multi threading”.

Let us consider the situation, When we go to a movie theater, generally a


person is there at the door-checking and cutting the tickets. When we enter
the hall, there is another person who shows the seats to us. Suppose there
is only one person doing these two tasks. He has to first cut the ticket and
then come along with us to show the seat. Then he goes back to the door to
cut the second ticket and then again enter the hall to show the seat for the
second ticket. If he is does the things one by one, it takes a lot of time, and
even though the show is over, there will be still a few people left outside the
door waiting to enter the hall. So two persons are required for this purpose.
First person will cut the ticket and second one will show the seat.

class MultiTasking extends Thread


{
String str;
MultiTasking(String str)
{
this.str=str;
}
public void run()
{

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

for(int i=1;i<=10;i++)
{
System.out.println(str+" : "+i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
}
}
public static void main(String args[])
{
MultiTasking d = new MultiTasking("show the ticket");
MultiTasking d1= new MultiTasking("cut the ticket");
Thread t = new Thread(d);
Thread t1=new Thread(d1);
t.start();
t1.start();
}
}

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

Multiple Threads acting on single object:

In theater example we have used two threads on the two objects of


MutiTasking object. It is also possible to use two or more threads on a single
object. But in this case, sometimes we get unreliable results.

class Reserve implements Runnable


{
int available=1;
int wanted;
Reserve(int i)
{
wanted=i;
}
public void run()
{
System.out.println("Available Berths : "+available);
if(available>=wanted)
{
String name=(Thread.currentThread()).getName();
System.out.println(wanted +" Berths reserved for "+name);
try
{
Thread.sleep(1500);
available=available-wanted;
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
else
System.out.println(" sorry no berth u r very late..");
}
}
class MultiObject
{
public static void main(String args[])
{
Reserve obj=new Reserve(1);
Thread t=new Thread(obj);
Thread t1=new Thread(obj);
t.setName("First Person");
t1.setName("Second Person");

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

t.start();
t1.start();
}
}

Thread Synchronization:
When a thread is already acting on an object, preventing any other
thread from acting on the same object is called Thread Synchronization or
Thread Safe. The object on which the threads are synchronized is called
synchronized object. Thread synchronization is recommended when multiple
threads are used on the same object

Synchronized is keyword applied for methods and blocks not for


variables and classes. If method or a block is declared as synchronized at a
time only one thread is allowed to execute the synchronized method or
block. The advantage of synchronization is prevent data corruption and
security. Preventing more than one thread to act upon the same object
simultaneously is called thread synchronization, that object is called as
synchronized object or Mutex(Mutually Exclusive).

To synchronize the object there are two ways:

1. using synchronize block, we can synchronize a group of statements.

Syntax:
Synchronized(obj)
{
Statements;
}

2. By writing Synchronized keyword before method. We can synchronize the


entire method code.

Syntax:
Synchronized void method()
{
Statements;
}

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

The difference between synchronized block and synchronized method is


block is a group of statements in the method, where as synchronized
method is a method that act upon the entire method. If we use multiple
threads, it is recommended that to use synchronization.

class Reserve implements Runnable


{
int available=1;
int wanted;
Reserve(int i)
{
wanted=i;
}
public synchronized void run()
{
System.out.println("Available Berths : "+available);
if(available>=wanted)
{
String name=Thread.currentThread().getName();
System.out.println(wanted +" Berths reserved for"+name);
try
{
Thread.sleep(1500);
available=available-wanted;
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
}
else
System.out.println(" sorry no berth u r very late..");
}
}
class ThreadSyn
{
public static void main(String args[])
{
Reserve obj=new Reserve(1);
Thread t=new Thread(obj);
Thread t1=new Thread(obj);
t.setName("First Person");
t1.setName("Second Person");

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

t.start();
t1.start();
}
}

Thread Life Cycle


A thread is created using new Thread() statement and is executed by
start() method. The thread enters runnable state when sleep() or wait()
methods are used or when thread is blocked on I/O, it then goes into
runnable state, the thread comes back to the runnable state and continues
running state. The thread dies when it comes out of run() method.

The following figure shows the different states of thread in Life Cycle:

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

New / born state:


when the thread is created it is said to be in born state or a new state. A
thread is inactive in this state.

Ready/Runnable state :
when we call start() method on a thread the thread enters into ready /
runnable state. In this state the thread is active and it is eligible for
microprocessor time. All threads are waiting in the thread pool for
microprocessor time. The thread scheduler fixs the thread and give to the
processor.

Running state:
A thread is in running state if it is utilizing the micro processor time. There
are several ways to enter into the runnable state but there is only one way to
enter in running state.

Dead state:
when the thread execution is completed the thread enters into dead state.

Sleeping state:
When we call sleep() method on the executing thread the threads enters into
sleeping state and when the sleep interval expires automatically the thread
enters into the running state.

Waiting state:
Waiting state when we call wait() method on the thread the thread enters
into waiting state. When we call notify() or notifyall() methods the thread
enters into ready or runnable state.

Priorities of Threads:
Each thread has a priority, which helps the thread scheduler to decide
the order of sequence of thread execution i.e, whhen should which thread
run? By default the threads created, carry the same priority, due to which
java scheduler schedules them for the processor on FirstComeFirstServe
basis. Java follows preemptive sheduling policy like OS.

Threads can be given different priorities from 1 to 10. The thread with
more priority is given first preference by thread scheduler of JVM. The
thread scheduler of JVM allocates more microprecssor time than the thread
with less priority.

There are two methods that support priorities in Thread class


setPriority(int): we can set priority to a thread.
getPriority(int): We can retrieve the priority of a thread.

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

Priority constants and their corresponding values for threads

Constant Value Meaning

MIN_PRIORITY 1 Minimum priority a thread can have

NORM_PRIORITY 5 Default priority a thread can have

MAX_PRIORITY 10 Maximum priority a thread can have

class ThreadPriority extends Thread


{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(this.getName() +" : "+i);
}
}
public static void main(String args[])
{
ThreadPriority tp=new ThreadPriority();
ThreadPriority tp1=new ThreadPriority();
ThreadPriority tp2=new ThreadPriority();

//setting priorities
tp.setPriority(Thread.MIN_PRIORITY);
tp1.setPriority(Thread.MIN_PRIORITY+3);
tp2.setPriority(Thread.MAX_PRIORITY);

//getting priorities
System.out.println("First Thread Priority : "+tp.getPriority());
System.out.println("Second Thread Priority : "+tp1.getPriority());
System.out.println("Third Thread Priority : "+tp2.getPriority());
tp.setName("first thread ");
tp1.setName("second thread ");
tp2.setName("third thread ");
tp.start();
tp1.start();
tp2.start();
}
}

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

Inter Thread Communication or Thread Communication:


In some cases two or more threads should communicate with each
other. For example, a Consumer thread is waiting for a producer to produce
the data. When the producer thread completes production of data, then the
consumer thread should take that data and use it.

In the producer class, we take a StringBuffer object to store data. In this


case, we take some numbers from 1 to 10. These numbers are added to
StringBuffer object. We take another Boolean variable dataprodover and
initialize it to false. The idea is to make this dataprodover true when the
production of numbers is completed. Producing data is done by appending
numbers to StringBuffer using a for loop. This may take some time. When
appending is over, we come out of for loop and then store trure into
dataprodover.

Let us consider the following program.

class Communicate
{
public static void main(String args[])
{
Producer po=new Producer();
Consumer co=new Consumer(po);
Thread t1=new Thread(po);
Thread t2=new Thread(co);
t2.start();
t1.start();
}
}
class Producer extends Thread

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

{
StringBuffer sb;
boolean dover=false;
Producer()
{
sb=new StringBuffer();
}
public void run()
{
for(int i=1;i<=10;i++)
{
try{
sb.append(i+" ");
Thread.sleep(100);
System.out.println("Still Appending");
}
catch(InterruptedException e){System.out.println(e);}
}
dover=true;
System.out.println("Data Production is Completed");
}
}
class Consumer extends Thread
{
Producer prod;
Consumer(Producer prod)
{
this.prod=prod;
}
public void run()
{
try {
while(!prod.dover)
{
Thread.sleep(10);
}
}
catch(InterruptedException e) { }
System.out.println("Produced Data is");
System.out.println(prod.sb);
}
}

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

In this way, the producer and consumer can communicate with each
other. But this is not an efficient way of communication. Why? Consumer
checks the dataprodover at some point of time and finds it false. So it goes
into sleep for the next 10milliseconds. Meanwhile the data production may
be over. But consumer comes out of sleep after 10 milliseconds and then
only it can find dataprodover is true. This means that there may be a time
delay of 1 to 9 milliseconds to receive the data after its actual production is
completed.

Inorder to improve the efficiency of communication between threads,


java.lang.Object class provides three methods

notify():This method releases an object and sends a notification to a waiting


thread that the object is available.

notifyAll(): This method releases an object and sends a notification to all


waiting threads that the object is available.

wait(): This method makes a thread wait for the object till it receives a
notification from a notify() and notifyAll().

class Communicate1
{
public static void main(String args[])
{
Producer obj1=new Producer();
Consumer obj2=new Consumer(obj1);
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t2.start();
t1.start();

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

}
}
class Producer extends Thread
{
StringBuffer sb;
boolean dataprodover=false;
Producer()
{
sb=new StringBuffer();
}
public void run()
{
synchronized(sb)
{
for(int i=1;i<=10;i++)
{
try{
sb.append(i+" ");
Thread.sleep(100);
System.out.println("appending");
}
catch(Exception e){ }
}
sb.notify();
}
}
}
class Consumer extends Thread
{
Producer prod;
Consumer(Producer prod)
{
this.prod=prod;
}
public void run()
{
synchronized(prod.sb)
{
try{
prod.sb.wait();
}
catch(InterruptedException e){ }

Department of Computer Science and Engineering S Kranthi Reddy


JAVA PROGRAMMING

System.out.println(prod.sb);
}
}
}

Department of Computer Science and Engineering S Kranthi Reddy

You might also like