0% found this document useful (0 votes)
77 views33 pages

JPR CH 4

The document discusses different types of errors and exceptions in Java programs. It explains syntax errors, logical errors, runtime errors, and compile time errors. It also covers checked and unchecked exceptions, and how to handle exceptions using try, catch, throw, throws, and finally keywords in Java.

Uploaded by

Good
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views33 pages

JPR CH 4

The document discusses different types of errors and exceptions in Java programs. It explains syntax errors, logical errors, runtime errors, and compile time errors. It also covers checked and unchecked exceptions, and how to handle exceptions using try, catch, throw, throws, and finally keywords in Java.

Uploaded by

Good
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Chapter 4 – Exception Handling and Multithreading

Errors

1) Errors are the mistakes that can make a program go wrong.


2) Error may produce a wrong results or abruptly terminates the execution of the
program or may cause the system to crash.
3) Detecting and managing the errors is very important during the program execution.
4) It is obvious responsibility of a programmer to deal with all kinds of errors.
5) Errors are the critical conditions that occur due to the lack of the system resources, and
it can not be handled by the code of the program. Errors can not be recovered by any
means because they can not be created, thrown, caught or replied. Errors are caused
due to the catastrophic failure which usually can not be handled by your program.
6) Errors are always of unchecked type, as compiler do not have any knowledge about its
occurrence. Errors always occur in the run-time environment.

7) Types of errors :
1. Syntax error
2. Logical error
3. Runtime error
4. Compile time error

1. Syntax error– These types of error occurred due to incorrect grammar in the
programming language. Syntax error is found during the execution of the program.

Some syntax error are:

1) Error in structure
2) Missing operators
3) Unbalanced parenthesis, square brackets and curly braces
4) Missing semicolons
5) Misspelled variable and function names
6) Incorrect format in semicolon and loop statements.

2. Logical error –These errors are due to the mistakes made by the programmer. It will
not be detected by a compiler nor by the JVM. Errors may be due to wrong idea or
concept used by a programmer while coding.

1) Multiplying when you should be dividing

Prof. R. S. Patil 1
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

2) Adding when you should be subtracting


3) Opening and using data from the wrong file
4) Displaying the wrong message

3. Runtime error – Runtime errors occur during the execution of program. These errors
are errors which occur when the program is running. Run time errors are not detected
by the java compiler. It is the JVM which detects it while the program is running.

1) Trying to divide by a variable that contains value zero.


2) Trying to open a file that does not exist.

4. Compile time error - Semantic errors are compile time errors. The compiler will list
the line number and even the word that is causing the issue. These types of error are
detected at compile time. Most of the compile time errors are scope and declaration
error.

1) Incompatible types of operands


2) Undeclared or multiple declared variables
3) Not matching of actual argument with formal argument

Difference between Error and Exception :-

Error Exception
1. Impossible to recover from an error. 1. Possible to recover from exceptions.
2. Errors are of type ‘unchecked’. 2. Exceptions can be either ‘checked’ or ‘unchecked’.
3. Occur at runtime. 3. Can occur at compile time or run time.
4. Caused by the application running
4. Caused by the application itself.
environment.
5.They are defined in java.lang.Error 5.They are defined in java.lang.Exception package
package.

6.Examples :
6.Examples : Checked Exceptions : SQLException, IOException
java.lang.StackOverflowError, Unchecked Exceptions :
java.lang.OutOfMemoryError ArrayIndexOutOfBoundException,
NullPointerException, ArithmeticException.

Prof. R. S. Patil 2
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Exception Handling in java


What is Exception in Java..?
Dictionary Meaning: Exception is an abnormal condition.

1. Definition - An exception is an event that disrupts the normal flow of the


program.

2. An exception is an unwanted and unexpected event, which occurs during the


execution of a program i.e. at runtime , that disturbs or interrupts the normal
flow of the program.

3. It is an object which is thrown at runtime.


4. All the exceptions are usually handled by the Java compiler.
5. When an exception occurs, compiler provides an error message and terminates the
program.
6. Suppose there are 5 statements in your program and there occurs an exception at
statement 3, the rest of the code will not be executed i.e. statement 4 to 5 will not be
executed.

statement 1;
statement 2;
statement 3; //exception occurs
statement 4;
statement 5;

7. If we perform exception handling, the rest of the statement will be executed. That is
why we use exception handling in Java.

What is Exception Handling : -


Exception Handling is one of the powerful mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc. So that
normal flow of the application can be maintained.

Hierarchy of Java Exception classes : -


The java.lang.Throwable class is the root class of Java Exception hierarchy which is
inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are
given below:

Prof. R. S. Patil 3
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Types of Java Exception : -


1) Checked Exception
2) Unchecked Exception
3) Error

1) Checked Exception :-

1. The classes which directly inherit Throwable class except RuntimeException and
Error are known as checked exceptions. e.g. IOException, SQLException etc.
2. Checked exceptions are checked at compile-time.
3. If some code within a method throws a checked exception, then the method must
either handle the exception or it must specify the exception using throws keyword.
4. At run time, these exceptions may occur or not but it is responsibility of
programmer to compulsory handle these exceptions in the program by writing
exception handling code.
5. Example –IOException, SQLException, ClassNotFoundException, InterruptException
etc.

Prof. R. S. Patil 4
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

2) Unchecked Exception :-

1. The classes which inherit RuntimeException are known as unchecked exceptions.


2. Unchecked exceptions are checked at run-time.
3. Hence, Compiler does not check whether the method in which exception may occur
contains the exceptions handling code or not.
4. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

3) Error :-

1. Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Exception Handling Tasks :


1. Find the problem (Hit the execution)
2. Inform that an error has occurred (Throw the execution)
3. Receive the error information(Catch the exception)
4. Take corrective actions (Handle the exception)

Java provides following five keyword to handle the exceptions:

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

Prof. R. S. Patil 5
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

1. try

1. A keyword “try” is used for block of code that causes an error condition and
“throws” an exception.
2. The try block contains a set of statements where an exception can occur.
3. It is always followed by a catch block, which handles the exception that occurs in the
associated try block.
4. Java try block must be followed by either catch blocks or finally block or both.

2. catch

1. A keyword “catch” is used for block of code that “catches” the exception
thrown by the “try” block and handles it properly.
2. This block is also known as Exception Handler.
3. A catch block is where you handle the exceptions and this catch block must be used
after the try block.
4. A single try block can have multiple catch blocks associated with it. You can catch
different exceptions in different catch blocks.

Syntax :-

try
{
Statement ; //generates an exception
}
catch(Exception-type e)
{
Statement ; //processes the exception
}

Problem without exception handling:-


Let's try to understand the problem if we don't use a try-catch block.

Example-1-
class Test
{
public static void main(String args[ ])
{
int a = 100 , b = 0, c ;
c = a / b;
System.out.println( c );
}
}
Prof. R. S. Patil 6
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Output-
Exception in thread "main" java.lang.ArithmeticException: / by zero
At Test.main(Test.java 6)

Above program is not executed. There can be 100 lines of code after exception. So all the
code after exception will not be executed.

Solution by exception handling:-

Let's see the solution of the above problem by a java try-catch block.

Example-2-

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

try
{
int a = 100 , b = 0 , c ;
c = a / b;
System.out.println( c );
}

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

System.out.println(" Hello ");


}
}

Output-
java.lang.ArithmeticException: / by zero
Hello

Now, as displayed in the above example, the code after catch is executed, i.e., the Hello
statement is printed.

Prof. R. S. Patil 7
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Examples:-

If Exception is not occur then catch If Exception is occur then catch


block is not executed. block is executed.

class Test class Test


{ {
public static void main(String args[ ]) public static void main(String args[ ])
{ {
System.out.println("1"); System.out.println("1");
try try
{ {
System.out.println("2"); System.out.println("2");
int a =100, b=2 , c; int a =100, b=0 , c;
System.out.println("3"); System.out.println("3");
c = a / b; c = a / b;
System.out.println("4"); System.out.println("4");
System.out.println( c ); System.out.println( c );
System.out.println("5"); System.out.println("5");
} }
catch(ArithmeticException e) catch(ArithmeticException e)
{ {
System.out.println("6"); System.out.println("6");
System.out.println( e ); System.out.println( e );
System.out.println("7"); System.out.println("7");
} }
System.out.println("hello"); System.out.println("hello");
} }
} }
Output - 1 Output - 1
2 2
3 3
4 6
50 java.lang.ArithmeticException / by zero
5 7
hello hello

Multiple catch blocks:-


1. To handle multiple exceptions, we have to create multiple catch blocks.
2. A try block can be followed by multiple catch blocks.
3. Each catch block must contain a different exception handler.
4. So, if you have to perform different tasks at the occurrence of different exceptions,
use java multi-catch block.
Prof. R. S. Patil 8
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

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

Let's see a simple example of java multi-catch block.

Example-1-

class MultipleCatchEx
{
public static void main(String args[ ])
{
try
{
int a[ ] = new int[5];
a [5] = 30/0;
}

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-
Arithmetic Exception occurs
rest of the code

3. finally :-

1) Java finally block is a block that is used to execute important code or to put
“cleanup” code such as closing connection, stream etc.
2) Java finally block is always executed whether exception is handled or not.
3) Java finally block follows try or catch block.
4) It is written immediately after the try block or after the last catch block.
Prof. R. S. Patil 9
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Syntax of Java try-catch and finally :

try
{ ……..
}
catch(Exception-type e)
{ ……..
}
finally
{
…………… // optional
}

Example-1-

class Test
{
public static void main(String args[ ])
{
try
{
int a = 100, b = 2, c ;
c = a / b;
System.out.println( c );
}

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

finally
{
System.out.println(" I am in finally block");
}
}
}

Output - 50
I am in finally block

But if we put b = 0 then Exception occur in the program then catch block handle the
exception and we will get the following output

java.lang.ArithmeticException / by zero
I am in finally block

Prof. R. S. Patil 10
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

4.throw keyword:-

1) The Java throw keyword is used to explicitly throw an exception.


2) All methods in java use the ‘throw’ statement explicitly to throw an exception from
a method or any block of code.
3) throw can be used for either checked or unchecked exception.
4) It is mainly used to throw custom exception.

Syntax :

throw new ExceptionClassName( …..)

In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.

Example-1-

public class Test


{
static void validate(int age)
{
if (age < 18)
throw new ArithmeticException (" not valid ");
else
System.out.println("welcome to vote");
}
public static void main(String args[ ])
{
validate(13 );
System.out.println("rest of the code...");
}
}

Output-
Exception in thread main java.lang.ArithmeticException: not valid

5. throws keyword:-

1) The Java throws keyword is used to declare an exception.


2) It gives an information to the programmer that there may occur an exception so it is
better for the programmer to provide the exception handling code so that normal
flow can be maintained.
3) Multiple exceptions can be declared through throws.

Prof. R. S. Patil 11
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Syntax :

type method_name( parameters ) throws exception_list


{
//definition of method
}
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.

Example-1-

class Test
{
static void check( ) throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException(" demo ");
}
public static void main(String args[ ])
{
try
{
check( );
}
catch(ArithmeticException e)
{
System.out.println("caught : " + e);
}
}
}
Output-
Inside check function
caught : java.lang.ArithmeticException: demo

Difference between throw and throws :-

No. throw throws


Java throw keyword is used to Java throws keyword is used to declare an
1
explicitly throw an exception. exception.
Checked exception cannot be Checked exception can be propagated with
2
propagated using throw only. throws.
3 throw is followed by an instance. throws is followed by class.
4 throw is used within the method. throws is used with the method signature.

Prof. R. S. Patil 12
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

You can declare multiple exceptions e.g.


You cannot throw multiple
5 public void method( )throws IOException,
exceptions.
SQLException.

Built-in Exceptions:-

1) Inside the standard package java.lang, Java defines several exception classes.
2) The most general built-in exceptions are subclasses of the standard type
RuntimeException.
3) Since java.lang is implicitly imported into all Java programs, most exceptions
derived from RuntimeException are automatically available.

Unchecked ( Runtime ) Exception

No. Exception Meaning


1 ArithmeticException Arithmetic error, such as divide by zero.
2 ArrayIndexOutOfBoundsException Array index is out-of-bounds
Assignment to an array element of an
3 ArrayStoreException
incompatible type
4 ClassCastException Invalid cast
5 IllegalArgumentException illegal argument used to invoke a method
6 IndexOutOfBoundsException Some type of index is out-of-bounds
7 NullPointerException Invalid use of a null reference
Invalid conversion of a string to a numeric
8 NumberFormatException
format
Attempt to index outside the bounds of a
9 StringIndexOutOfBounds
string
10 TypeNotPresentException Type not found

Checked ( Compile time) Exception

No. Exception Meaning


1 ClassNotFoundException Class not found.
2 IllegalAccessException Access to a class is denied.
One thread has been interrupted by
3 InterruptedException
another thread.
4 NoSuchFieldException A requested field does not exist.
5 NoSuchMethodException A requested method does not exist.

Prof. R. S. Patil 13
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Chained Exceptions:-
1) Chained exception feature allow you to relate one exception with another exception,
i.e one exception describes cause of another exception.
2) For example, consider a situation in which a method throws an
ArithmeticException because of an attempt to divide by zero but the actual cause of
exception was an I/O error which caused the divisor to be zero.
3) The method will throw only ArithmeticException to the caller. So the caller would
not come to know about the actual cause of exception. Chained Exception is used in
such type of situations.
4) Two new constructors and two new methods were added to Throwable class to
support chained exception.

1. Throwable( Throwable cause )


2. Throwable( String str, Throwable cause )

In the first form, the paramter cause specifies the actual cause of exception. In the second
form, it allows us to add an exception description in string form with the actual cause of
exception.

getCause( ) and initCause( ) are the two methods added to Throwable class.

1. getCause( ) method returns the actual cause associated with current


exception.
2. initCause( ) set an underlying cause(exception) with invoking exception.

Example-1-

import java.io.IOException;
public class ChainedException
{
public static void divide(int a, int b)
{
if(b == 0)
{
ArithmeticException ae = new ArithmeticException("top layer");
ae.initCause( new IOException("cause") );
throw ae;
}
else
{
System.out.println(a/b);

Prof. R. S. Patil 14
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

}
}

public static void main(String args[ ])


{
try
{
divide(5, 0);
}
catch(ArithmeticException ae)
{
System.out.println( "caught : " + ae);
System.out.println("actual cause: " + ae.getCause( ));
}
}
}
Output-
caught: java.lang.ArithmeticException: top layer
actual cause: java.io.IOException: cause

Creating Own Exceptions (Custom Exceptions):-


1) If you are creating your own Exception that is known as custom exception or user-
defined exception.
2) Java custom exceptions are used to customize the exception according to user need.
3) By the help of custom exception, you can have your own exception and message.

Let's see a simple example of java custom exception.

Example-1-

class InvalidAgeException extends Exception


{
InvalidAgeException(String s)
{
super(s);
}
}
class CustomEx
{
static void validate(int age)throws InvalidAgeException
{
if(age < 18)
throw new InvalidAgeException("not valid");
else
Prof. R. S. Patil 15
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

System.out.println("welcome to vote");
}
public static void main(String args[ ])
{
try
{
validate(13);
}
catch(Exception m)
{
System.out.println("Exception occured: " + m);
}
System.out.println("rest of the code...");
}
}

Output-
Exception occurred: InvalidAgeException: not valid
rest of the code…

Multithreading Programming :-

1) Multithreading in java is a process of executing multiple threads (tasks)


simultaneously.
2) Each piece of such a program is called a thread, and each thread defines a separate
path of execution.
3) A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
4) However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.
5) Java Multithreading is mostly used in games, animation, etc.

Advantages of 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.

Prof. R. S. Patil 16
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Multitasking :-

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


utilize the CPU. Multitasking can be achieved in two ways:

1. Process-based Multitasking (Multiprocessing)


2. Thread-based Multitasking (Multithreading)

Difference between Process and Thread :

No. Process Thread


Process has its own main memory for Thread use process’s main memory for
1
execution. execution and share it with other threads.
Process is considered as a Thread is considered as a lightweight
2
heavyweight component. component.
3 Context switch time is more. Context switch time is less.
Inter process communication is
4 Inter thread communication is simple.
complex.
5 One process can have multiple threads One thread can not have multiple process.

1. Process-based Multitasking (Multiprocessing)

1) Multiple tasks are executed simultaneously by multiple applications


2) Each process has an address in memory. In other words, each process allocates a
separate memory area.
3) A process is heavyweight.
4) Cost of communication between the process is high.
5) Switching from one process to another requires some time for saving and loading
registers, memory maps, updating lists, etc.

Prof. R. S. Patil 17
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

6) For example: Typing in Excel, Listening music, drawing diagram in paint and
downloading file from internet at the same time. Here in example we can clearly see
that all applications are independent.

Multiprocessing

2. Thread-based Multitasking (Multithreading)

1) Multiple tasks are executed simultaneously by single application


2) Threads share the same address space.
3) A thread is lightweight.
4) Cost of communication between the thread is low.
5) For Example, When you use a word processor you perform a many different tasks
such as printing, typing, spell checking and so on.

Printing Typing Spell Checking

Prof. R. S. Patil 18
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Thread :-

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


execution.

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

As shown in the above 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.

Note : At a time one thread executed only.

Life cycle of a Thread :-

A thread can be in one of the five states. The life cycle of the thread in java is controlled by
JVM. The java thread states are as follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated (Dead)
Prof. R. S. Patil 19
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

New thread

killed thread

Idle thread

1. New :-
• A thread begins its life cycle in the new state. It remains in this state until
the program start( ) the thread. It is also referred to as born thread.

2. Runnable :-
• After invocation of start( ) method on new thread, the thread becomes
runnable.

3. Running :-
• A thread is in running state if the thread scheduler has selected it.

4. Blocked /Waiting /Not Runnable :-


• A thread is in waiting state if it waits for another thread to perform a task.
• This is the state when the thread is still alive, but is currently not eligible
to run.

5. Terminated/Dead :-
• A thread enter the terminated state(or dead state) when it complete its
task. Or its run( ) method exits.

Prof. R. S. Patil 20
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

How to create Thread :-


There are two ways to create a thread:

1. By implementing Runnable interface


2. By extending Thread class

Thread Class :-

 Thread class provide constructors and methods to create and perform operations on
a thread.
 Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class :-


- There are two ways to create a thread:

• Thread( )
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)

Commonly used Methods of Thread class::-

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


2. public void start( ): starts the execution of the thread. JVM calls the run( ) method
on the thread.
3. public void sleep(long milliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void wait( ): tells the calling thread to give up the monitor and go to sleep
until some other thread enters the same monitor and calls notify( ).
5. public void notify( ): wakes up a thread that called wait( ) on the same object.
6. public void notifyAll( ): wakes up all the threads that called wait( ) on the same
object. One of the threads will be granted access.
7. public void yield( ): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
8. public void suspend( ): is used to put the thread in suspended state.
9. public void resume( ): is used to resume the suspended thread.

Prof. R. S. Patil 21
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

10. public void stop( ): is used to stop the thread.


11. public int getPriority( ): returns the priority (integer value) of the thread.
12. public int setPriority(int priority): changes the priority of the thread.
13. public String getName( ): returns the name of the thread.
14. public void setName(String name): changes the name of the thread.

1. By implementing Runnable interface :-

• The easiest way to create a thread is to create a class that implements the Runnable
interface.
• To implement Runnable interface, a class need only implement a single method
called run( ), which is declared like this:

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

start( ) method of Thread class is used to start a newly created thread.

Java Thread Example by implementing Runnable interface

Example-1-

class A implements Runnable


{
public void run( )
{
System.out.println("thread is running...");
}
public static void main(String args[ ])
{
A a1 = new A( );
Thread t1 = new Thread( a1);
t1.start( );
}
}
Output-
thread is running…

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

Prof. R. S. Patil 22
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Example-2-

class x1 implements Runnable


{
public void run( )
{
try
{
for(int i = 1; i<=5; i++)
{
System.out.println(" Thread 1.... ");
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{}
}
}
class x2 implements Runnable
{
public void run( )
{
try
{
for(int i =1; i<=5; i++)
{
System.out.println(" Thread 2.... ");
Thread.sleep(5000);
}
}
catch(InterruptedException e)
{}
}
}
class RunnableEx
{
public static void main(String args[ ])
{
x1 a = new x1( );
Thread t1 = new Thread( a );
t1.start( );
Prof. R. S. Patil 23
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

x2 b = new x2( );
Thread t2 = new T hread( b );
t2.start( );
}
}

Output-

Thread 1….
Thread 2….
Thread 1….
Thread 1….
Thread 1….
Thread 1….
Thread 2….
Thread 2….
Thread 2….
Thread 2….

2. By extending Thread class :-

• The second way to create a thread is to create a new class that extends Thread, then
override the run( ) method and then to create an instance of that class. The run( )
method is what is executed by the thread after you call start( ).

Java Thread Example by extending Thread class

Example-1-

class A extends Thread


{
public void run( )
{
System.out.println("thread is running...");
}
public static void main(String args[ ])
{
A a1 = new A( );
a1.start( );
}
}
Output-
thread is running…
Prof. R. S. Patil 24
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Example-2-

class x1 extends Thread


{
public void run( )
{
try
{
for(int i = 1; i<=5; i++)
{
System.out.println(" Thread 1.... ");
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{}
}
}
class x2 extends Thread
{
public void run( )
{
try
{
for(int i =1; i<=5; i++)
{
System.out.println(" Thread 2.... ");
Thread.sleep(5000);
}
}
catch(InterruptedException e)
{}
}
}
class xyz
{
public static void main(String args[ ])
{
for(int i=1; i<=5; i++)
{
System.out.println(" Thread Main.... ");
}
x1 a = new x1( );
a.start( );
x2 b = new x2( );
b.start( );
} }
Prof. R. S. Patil 25
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Output-
Thread main….
Thread main….
Thread main….
Thread main….
Thread main….
Thread 1….
Thread 2….
Thread 1….
Thread 1….
Thread 1….
Thread 1….
Thread 2….
Thread 2….
Thread 2….
Thread 2….
Thread 2….

Thread Priority and Methods :-

• Each thread have a priority. Priorities are represented by a number between 1 and
10.
• In most cases, thread scheduler schedules the threads according to their priority
(known as preemptive scheduling).
• But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.

3 constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

1) The value of MIN_PRIORITY is 1.


2) Default priority(NORM) of a thread is 5.
3) The value of MAX_PRIORITY is 10.

Prof. R. S. Patil 26
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Example-1-

class Example extends Thread


{
public void run( )
{
System.out.println("running thread name is: "+ Thread.currentThread( ).getName( ));
System.out.println("running thread priority is: "+ Thread.currentThread( ).getPriority( ));
}

public static void main(String args[ ])


{
Example m1 = new Example( );
Example m2 = new Example( );

m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);

m1.start( );
m2.start( );
}
}
Output- running thread name is : Thread-0
running thread priority is : 10
running thread name is : Thread-1
running thread priority is : 1

Synchronization :-
1) Synchronization in java is the capability to control the access of multiple threads to
any shared resource.
2) Java Synchronization is better option where we want to allow only one thread to
access the shared resource.

Why use Synchronization :-

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Prof. R. S. Patil 27
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Types of Synchronization :-

There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Understanding the problem without Synchronization

As shown in following example, there is no synchronization, so output is inconsistent.


Example-1-

class Table
{
void printTable(int n) //method not synchronized
{
for(int i=1; i<=5; i++)
{
System.out.println(n * i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);}
}
}
}

class MyThread1 extends Thread


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

Prof. R. S. Patil 28
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

class MyThread2 extends Thread


{
Table t;

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

class SynchroEx
{
public static void main(String args[ ])
{
Table obj = new Table( ); //only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start( );
t2.start( );
}
}
Output-
5
100
10
200
15
300
20
400
25
500

Java synchronized method :-

• If you declare any method as synchronized, it is known as synchronized method.


• Synchronized method is used to lock an object for any shared resource.
• When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.

Prof. R. S. Patil 29
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

Example-1-

class Table
{
synchronized void printTable(int n) // synchronized method
{
for(int i=1; i<=5; i++)
{
System.out.println(n * i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);}
}
}
}

class MyThread1 extends Thread


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

class MyThread2 extends Thread


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

Prof. R. S. Patil 30
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

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

Output-

5
10
15
20
25
100
200
300
400
500

Inter-thread communication in Java :-

1. In multithreading sometimes output generated by one thread acts as input for another
thread. And when the output is used by second thread, the first thread has to generate
another output.
2. Here the question is ; how second thread will come to know that the first thread has
created new output and also how first thread will know that the output generated by it
is used by second thread.
3. For this purpose in initial days, concept of polling was used in which a continues loop
was running to check the values. But this waste many CPU cycles and makes the
implementation inefficient. Hence java gives the solution of inter-thread
communication.
4. To avoid polling, Java uses three methods, namely, wait( ), notify( ) and notify( ).

Example-1-

Prof. R. S. Patil 31
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

class Customer
{
int amount = 10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount < amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait( );
}
catch(Exception e)
{
}
}
this.amount - = amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount)


{
System.out.println("going to deposit...");
this.amount + = amount;
System.out.println("deposit completed... ");
notify( );
}
}

class Test
{
public static void main(String args[ ])
{
final Customer c = new Customer( );
new Thread( )
{
public void run( )
{
c.withdraw(15000);
}
Prof. R. S. Patil 32
4th Semester-JPR[22412] Chapter-4 Exception Handling and Multithreading

}.start( );

new Thread( )
{
public void run( )
{
c.deposit(10000);
}
}.start( );
}
}

Output-
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

Deadlock in java:-

1. Deadlock in java is a part of multithreading.


2. Deadlock can occur in a situation when a thread (say T1) is waiting for an object lock,
that is acquired by another thread (say T2) and second thread (T2) is waiting for an
object lock that is acquired by first thread (T1).
3. Since, both threads are waiting for each other to release the lock, the condition is
called deadlock.

Prof. R. S. Patil 33

You might also like