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

JPR Unit 4

Uploaded by

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

JPR Unit 4

Uploaded by

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

Unit – IV

Exception Handling and Multithreading


08 Hours
12 Marks

4.1 Errors and Exceptions

Beginner programmers are rarely able to successfully execute their


programs in first effort. Generally they commit while developing and typing
programs. These mistakes are called errors.
There are two types of errors
- Compile-time
time Errors
- Run-time Errors

All the syntax errors are detected by Java compiler. These errors are called
compile-time errors.. Until and unless we clear compile compile-time
time errors from a
program, byte-code
code (.class file) will not be created for th that program. Some
examples of compile-time errors are semicolon missing, mismatch of braces, use of
undeclared variables etc.
After compiling a java program successfully, byte
byte-code
code (class file) is created.
Interpreter runs this class file. But even then sometimes the program generates
wrong output. This happens due to incorrect logic. This is called logical error (This
type of error is to be corrected by programmer by correcting the logic). Also,
sometimes program terminates due to errors like divide by zero. Both these
situations are referred to run-time errors. Some common run-time time errors are
divide by zero, accessing element which is out of bound of array, converting
invalid string to a number etc.
Exception is a condition caused due to occurrence of run run-time
time error. This
may be due to violation of rules of Java language or due to constraints of the java
execution environment. While executing a program, if exceptional condition (like
divide by zero) occurs, exception object is created by the java run-time
time system and
is thrown. Exception can also be generated manually by a program code.
In java, Throwable class woks as root for java’s error and exception
hierarchy as shown in following figure.

Throwable

Exception Error

Figure 4.1: Error & Exception Hierarchy in Java


One more difference in E Error
rror & Exception is that, Error is a critical
condition that cannot be handled by program code whereas Exception exceptional
situation that can be handled by program code.
Some common Java Exceptions are,
- ArithmeticException (mathematical errors like dividede by 0)
- ArrayIndexOutOfBoundsException (try to access bad array index)
- ArrayStoreException (try to store wrong type of data in array)
- NegativeArraySizeException (array creation with negative size)
- FileNotFoundException (try to open file which does not exist)
- IOException (general Input/ Output failure)
- NullPointerException (try to reference a null object)
- IllegalArgumentException (illegal argument while invoking method)
- NumberFormatException (when conversion between strings and
numbers fail)
- OutOfMemoryException
xception ((not enough memory to allocate new object)
- SecurityException (applet tries to perform operation which is not
allowed by browser’s security setting)
- StackOverFlowException (system runs out of stack space)
- StringIndexOutOfBoundException (try to access a nonexistent character
position in a string)
These are built-in
in exceptions in Java.

4.1.1 Process of handling exception


If exception object is not caught and handled properly, program displays
error message and terminates its execution abruptly. Iff we want to execute
remaining part of the program (in such situation), we should handle the exception
thrown by the program. This process involves various tasks as,
- Find the problem (Hit the exception)
- Inform that error has occurred (Throw the exception)
- Receive error information (Catch the exception)
- Take corrective action (Handle the exception)
This can be achieved through two blocks – one for detecting error situation
& throwing the exception and other for catching the exception & taking suitable
action. These two blocks are referred as try block and catch black respectively.
They are shown in following figure.

try block
• Statements that cause exception

Throw exception object

catch block (catch exception)


• Statements that handle the exception

Figure 4.2: Exception Handling


We can use keyword try for defining a ‘try block’ and keyword catch for
defining ‘catch block’. It is mandatory to have at least one ‘catch block’
immediately after ‘try block’.
Syntax for defining try block and catch block is given below.

try
{
Statements that may generate/cause exception
}
catch(Exception-type obj-name)
{
Statements for processing the caught exception
}

We may write multiple statements (those may cause exception) in try block.
Multiple statements may also be written in catch block for handling the caught
exception.
As observed in the above syntax, catch block looks like a method accepting
one parameter. If this parameter matches with the thrown exception object,
statements in the catch block are executed. Otherwise default exception handler of
java run-time environment will terminate the program execution.

Example 1:
class Unit4_1
{
public static void main(String args[ ])
{
int p, q, r, s;
p = 30;
q = 3;
r = 3;
try
{
s = p / (q – r);
System.out.println(“Result is ”+s);
System.out.println(“At the end of try block”);
}
catch(ArithmeticException e)
{
System.out.println(“You should not divide a number by 0”);
System.out.println(“At the end of catch block”);
}
System.out.println(“At the end of main method”);
}
}

Sample Output:
You should not divide a number by 0
At the end of catch block
At the end of main method
Example 2:
class Unit4_2
{
public static void main(String args[ ])
{
int a[]=new int[]{12,34,44,14};
int i;
System.out.println(“Array elements are:”);
try
{
for(i=0;i<8;i++)
{
System.out.println(a[i]);
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Accessing out of bound array element”);
}
System.out.println(“Thank you for using this program”);
}
}

Sample Output:
Array elements are:
12
34
44
14
Accessing out of bound array element
Thank you for using this program

We may also display description of the caught exception by passing the


exception object in println( ) method. For example, we may replace the catch block
of example 2 as shown below.
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Exception description: ”+e);
}
Due to this change the output of the program will change as shown below (it
will display the description of the caught exception).
Array elements are:
12
34
44
14
Exception description: java.lang.ArrayIndexOutOfBoundsException: 6
Thank you for using this program
4.1.2 Nested try blocks
We may use try block within another try block. This concept is called nested
try block. Each try block requires at least one matching catch block. An example
program is shown below.

Example:
class Unit4_3
{
public static void main(String args[ ])
{
int a[]=new int[]{12,34,44,14};
int i, p, q, r, s;
p = 30;
q = 3;
r = 3;
try
{
System.out.println(“Array elements are:”);
for(i=0;i<4;i++)
{
System.out.println(a[i]);
}
try
{
s = p / (q – r);
System.out.println(“Result is ”+s);
System.out.println(“At the end of try block 2”);
}
catch(ArithmeticException e)
{
System.out.println(“You should not divide a number by 0”);
System.out.println(“At the end of catch block for try block 2”);
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Accessing out of bound array element”);
System.out.println(“At the end of catch block for try block 1”);
}
System.out.println(“At the end of main method”);
}
}

Sample Output:
Array elements are:
12
34
44
14
You should not divide a number by 0
At the end of catch block for try block 2
At the end of main method

4.1.3 Multiple catch blocks for single try block


It may happen that statements in try block may create different exceptional
situations. So, a single try block may have multiple catch blocks for catching
different exception objects for different exceptional situations. An example
program is shown below.

Example:
class Unit4_4
{
public static void main(String args[ ])
{
int a[]=new int[]{12,34,44,14};
int i, p, q, r;
p = 30;
q = 3;
r = 3;
try
{
a[5] = p / (q – r);
System.out.println(“Result of division is stored in array”);
}
catch(ArithmeticException e)
{
System.out.println(“You should not divide a number by 0”);
System.out.println(“At the end of catch block 1”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Accessing out of bound array element”);
System.out.println(“At the end of catch block 2”);
}
System.out.println(“At the end of main method”);
}
}

Sample Output:
You should not divide a number by 0
At the end of catch block 1
At the end of main method

4.1.4 Using finally statement


We may have a finally block after all the catch blocks (or even we may have
try block immediately followed by finally block). The finally block is always
executed regardless of whether the exception is thrown or not. It may happen that
there are multiple catch blocks, exception is thrown by try block and not a single
catch block is able to catch the exception. In such situation also, finally block is
executed. Even if any catch block is executed, finally block is also executed. These
characteristics can be easily figured out in the following figure.

No Exception
occurred ?
Yes

No Exception
handled ?

Yes

finally block is
executed

Figure 4.3: finally block in Exception Handling


Due to all these characteristics of finally block, it is generally used to
perform housekeeping operations like closing file handles, freeing the allocated
resources etc.
Following example program shows methods that exits in different ways, but
each executes their finally block.

Example:
class Unit4_5
{
static void method1(int x, int y)
{
int z;
try
{
z = x / y;
System.out.println(“Result of division is: ”+z);
}
catch(ArithmeticException e)
{
System.out.println(“You should not divide a number by zero”);
}
finally
{
System.out.println(“Finally block is always executed”);
}
}

public static void main(String args[ ])


{
method1(10,5);
method1(20,0);
}
}

Sample Output:
Result of division is: 2
Finally block is always executed
You should not divide a number by 0
Finally block is always executed

4.1.5 Creating own exception


There are various built-in exceptions in java which can handle most
common exceptional situations. But there is a need to create our own exceptions
for handling exceptional situations specific to applications under development.
This facility is provided by java.
For doing so, we have to create a subclass of Exception class (Exception
class is already a subclass of Throwable class. The new subclass automatically
inherits all the methods of Throwable class such as fillInStackTrace( ), getCause(
), getLocalizedMessage( ), getMessage( ), initCause( ). Apart from this, we may
also create new methods.
Once the exception subclass is created, we may throw this new exception ny
using keyword throw with following syntax.
throw new exception_subclassname;

Following example programs show how we can create our own exception
and throw it.

Example 1:
class MyException1 extends Exception
{
MyException1(String message)
{
super(message);
}
}

class Unit4_6
{
public static void main(String args[ ])
{
try
{
throw new MyException1(“This is user-defined exception”);
}
catch(MyException1 e)
{
System.out.println(“Caught Exception”);
System.out.println(e.getMessage( ));
}
}
}

Sample Output:
Caught Exception
This is user-defined exception

Example 2:
import java.io.*;

class MyException2 extends Exception


{
MyException2(String message)
{
super(message);
}
}

class Employee
{
String name;
long salary;

public void getData( )


{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println(“Enter name of employee: ”);
name = br.readLine( );
System.out.println(“Enter salary of employee: ”);
salary = Integer.parseInt(br.readLine( ));
if(salary<0)
{
salary = 0;
throw new MyException2(“Salary cannot be negative”);
}
}
catch(IOException e)
{
System.out.println(“Caught Exception”);
System.out.println(e.getMessage( ));
}
catch(MyException2 e)
{
System.out.println(“Caught Exception”);
System.out.println(e.getMessage( ));
}
}

public void putData( )


{
System.out.println(“Name of employee: ”+name);
System.out.println(“Salary of employee: ”+salary);
}

public static void main(String args[ ])


{
Employee e1 = new Employee( );
e1.getData( );
e1.putData( );
}
}

Sample Output 1:
Enter name of employee:
Ajay
Enter salary of employee:
1200000
Name of employee: Ajay
Salary of employee: 1200000

Sample Output 2:
Enter name of employee:
Vijay
Enter salary of employee:
-250000
Caught Exception
Salary cannot be negative
Name of employee: Vijay
Salary of employee: 0

4.1.6 Chained Exceptions


With the help of this feature, an exception may be associated with another
exception. The benefit of this feature is that, second exception describes the cause
of first exception.
Following two constructors help in using chained exceptions.
1. Throwable(Throwable cause_exc)
Here cause_exc is the exception that causes current exception.
2. Throwable(String msg, Throwable cause_exc)
Here msg is the exception message and cause_exc is the exception
that causes current exception.

For supporting chained exception in Java, following methods are helpful


1. getCause( )
This method returns actual cause of occurrence of exception.
2. initCause(Throwable cause_esc)
This method sets the cause for the calling exception.

An example program is shown below which uses chained exception.

Example:
class Unit4_7
{
public static void main(String[] args)
{
try
{
NumberFormatException ex =
new NumberFormatException("Exception");

// Setting a cause of the exception


ex.initCause(new NullPointerException(
"This is actual cause of the exception"));

// Throwing an exception with cause.


throw ex;
}

catch(NumberFormatException e)
{
// displaying the exception
System.out.println(e);

// Getting the actual cause of the exception


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

Sample Output:
java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is actual cause of the exception

4.1.7 throws statement


If a method is capable of causing an exception, which it does not handle,
this must be specified in the method definition so that callers of this method can
handle such exception at their level. This can be done by using throws clause in
the method definition. We may include multiple exceptions (those are possible to
occur while executing the method) in the throws clause.
Syntax for using throws clause is as follows,
return-type method-name(parameter-list) throws exception-list
{
// method body
}
An example program is shown below.

Example:
class Unit4_8
{
static void method1( ) throws NullPointerException
{
System.out.println("In method1");
throw new NullPointerException("Demo");
}

public static void main(String[] args)


{
try
{
method1( );
}
catch(NullPointerException e)
{
System.out.println("Caught: "+e);
}
}
}
Sample Output:
In method1
Caught: java.lang.NullPointerException: Demo

4.2 Multithreaded Programming

Almost all the modern operating systems support facility of multitasking.


Multitasking is achieved in two ways – process-based and thread based. Process is
defined as an instance of a program. In other words, program in execution is
called process. So, process-based multitasking provides facility of running
multiple programs concurrently.
In thread-based multitasking, a program is divided into smaller
subprograms (threads), which may run concurrently. This results in greater level
of multitasking. Java also supports multithreading.
Generally a java program has a single flow of control. Such java program
runs sequentially. This type of program is called single-threaded program. A
single java program may be divided into smaller subprograms as discussed
previously. This results in multiple flows of control. Such program having
multiple flows of control is called as multithreaded program. Figure 4.4 shows
four threads – one main and three other threads. The other three threads are
started by main thread. All these four threads run concurrently.
Main Thread

-----
----
----------------
-----
--
--
--
----------
----

Start Start
Start

--- --- ---


---- ---- ----
-------- ---- --
---- Switching ---- Switching ---------
-- -- --
------ -- --
-- -- ----
--- ------ -----
-- -- --
Thread A Thread B Thread C

Figure 4.4: Multithreaded Program

4.2.1 Creating a thread


Threads can be created in two ways.
- By extending the Thread class
- By implementing the Runnable interface

4.2.1.1 Creating a thread by extending Thread class


For creating thread by extending Thread class, following steps need to be
followed. An example is also mentioned with each step.
1. Declare a class that extends Thread class.
class MyThread extends Thread
{
--
}
2. Override run( ) method of Thread class in the above class. Write the code
which is to be executed by the newly created thread in the run( )
method.
public void run( )
{
//code to be executed by thread
}
3. Create an object for the above class and call start( ) method for the
created object. (One can call the start( ) method in the constructor of
newly created class for invoking the run( ) method automatically on
creation of object of this class)
MyThread mt = new MyThread( );
mt.start( ); //run( )method gets invoked automatically

An example program using this method is shown below.

Example:
class MyThread1 extends Thread
{
public void run( )
{
int i;
System.out.println(“Starting MyThread1”);
for(i=1;i<=10;i++)
{
System.out.println(19*i); //Displays table of 19
}
System.out.println(“Exiting MyThread1”);
}
}
class Unit4_9
{
public static void main(String[] args)
{
int i;
System.out.println(“Starting main thread”);
MyThread1 mt1 = new MyThread1( );
mt1.start( );
for(i=2;i<=20;i=i+2)
{
System.out.println(i); //Displays even numbers
}
System.out.println(“Exiting main thread”);
}
}

Sample Output: (May change even on multiple execution)


Starting main thread
2
Starting MyThread1
4
19
6
38
57
76
8
10
95
114
12
133
14
16
152
171
18
190
Exiting MyThread1
20
Exiting main thread

4.2.1.2 Creating a thread by implementing Runnable interface


For creating thread by implementing Runnable interface, following steps
need to be followed. An example is also mentioned with each step.
1. Declare a class that implements Runnable interface.
class MyThread implements Runnable
{
--
}
2. Implement run( ) method. Write the code which is to be executed by the
newly created thread in the run( ) method.
public void run( )
{
//code to be executed by thread
}
3. Create an object for the above class, Create Thread object by passing the
object just created as parameter to constructor and call start( ) method
for the thread object.
MyThread mt = new MyThread( );
Thread t = new Thread(mt);
t.start( ); //run( )method gets invoked automatically

An example program using this method is shown below.

Example:
class MyThread2 implements Runnable
{
public void run( )
{
int i;
System.out.println(“Starting MyThread2”);
for(i=10;i>=1;i--)
{
System.out.println(i*i*i); //Displays cubes from 10 to 1
}
System.out.println(“Exiting MyThread2”);
}
}
class Unit4_10
{
public static void main(String[] args)
{
int i;
System.out.println(“Starting main thread”);
MyThread2 mt = new MyThread2( );
Thread t = new Thread(mt);
t.start( );
for(i=19;i>=1;i=i-2)
{
System.out.println(i); //Displays odd numbers from 19 to 1
}
System.out.println(“Exiting main thread”);
}
}

Sample Output: (May change even on multiple execution)


Starting main thread
19
17
Starting MyThread2
15
1000
13
729
11
512
9
343
7
216
5
125
3
64
1
27
Exiting main thread
8
1
Exiting MyThread2

4.2.2 Lift Cycle of Thread


From creation of thread to its termination, thread follows a cycle known as
life cycle of thread. It is shown in figure 4.5.
Newborn
stop( )
start( )
Active
thread yield( )
stop( )
Running ) Runnable Dead

suspend( ) resume( )
sleep( ) after specified time
stop( )
wait( ) notify( )
Blocked

Figure 4.5: Life cycle of a Thread


Various states through which a thread goes are discussed here. Also
various methods related to threads are also discussed.

Newborn State:
On creation, a thread enters in Newborn state. Thread in this state can
call start( ) method to become active. On calling start( ) method, run( ) method of
the thread is invoked automatically. Thread in this state may call stop( ) method
to enter in Dead state.

Runnable State:
Multiple threads may be in Runnable state. The threads in this state
are ready for execution and are waiting for availability of processor. (Processor can
run only one thread at an instance). Selection of a thread for allocation of
processor may be done on the basis of priority of the threads. If threads are having
same priority, threads may get selected on First Come First Serve basis.

Running State:
There can be only one thread in Running state at given instance of
time. Processor is allocated to such thread and it is being run by processor.
Running thread may invoke yield( ) method for giving control to another thread.
On invoking suspend( ) method, thread gets suspended. On invoking sleep(time)
method, thread sleeps for specified number of milliseconds. On invoking wait( )
method, threads goes in waiting. In all these cases, thread enters in Blocked state.

Blocked State:
When thread is prevented from entering in Runnable state, it is in
Blocked state. There are various reasons for entering this state. Thread may be
suspended, sleeping or waiting for being in this state. Suspended thread may
reenter in active state by invoking resume( ) method. Sleeping state will
automatically enter in active state on completion of sleeping time. Waiting state
may reenter in active state by invoking notify( ) method.
Dead State:
Thread may enter this state on its natural death. Thread in any state
may invoke stop( ) method for entering in this state.

The following example shows use of some thread methods.

class Thread1 extends Thread


{
public void run( )
{
int i;
for(i=0;i<10;i++)
{
if(i==2)
{
yield( );
}
System.out.println(“In thread 1, i = ”+i);
}
System.out.println(“Exiting Thread 1”);
}
}

class Thread2 extends Thread


{
public void run( )
{
int j;
for(j=0;j<10;j++)
{
System.out.println(“In thread 2, j = ”+j);
if(j==5)
{
stop( );
}
}
System.out.println(“Exiting Thread 2”);
}
}

class Thread3 extends Thread


{
public void run( )
{
int k;
for(k=0;k<10;k++)
{
System.out.println(“In thread 3, k = ”+k);
if(k==1)
{
try
{
sleep(200);
System.out.println(“Thread 3 sleeps for 200 milliseconds”);
}
catch(Exception e)
{

}
}
}
System.out.println(“Exiting Thread 3”);
}
}

class Unit4_11
{
public static void main(String[] args)
{
Thread1 t1 = new Thread1( );
Thread2 t2 = new Thread2( );
Thread3 t3 = new Thread3( );

System.out.println(“Started Thread 1”);


t1.start( );
System.out.println(“Started Thread 2”);
t2.start( );
System.out.println(“Started Thread 3”);
t3.start( );

System.out.println(“Exiting main thread”);


}
}

Sample Output: (May change even on multiple execution)


Started Thread 1
Started Thread 2
Started Thread 3
In thread 1, i = 0
In thread 1, i = 1
Exiting main thread
In thread 2, j = 0
In thread 2, j = 1
In thread 2, j = 2
In thread 2, j = 3
In thread 2, j = 4
In thread 2, j = 5
In thread 1, i = 2
In thread 3, k = 0
In thread 3, k = 1
In thread 1, i = 3
In thread 1, i = 4
In thread 1, i = 5
In thread 1, i = 6
In thread 1, i = 7
In thread 1, i = 8
In thread 1, i = 9
Exiting Thread 1
Thread 3 sleeps for 200 milliseconds
In thread 3, k = 2
In thread 3, k = 3
In thread 3, k = 4
In thread 3, k = 5
In thread 3, k = 6
In thread 3, k = 7
In thread 3, k = 8
In thread 3, k = 9
Exiting Thread 3

4.2.3 Thread Exceptions


From creation of thread to its termination, thread follows a cycle known as
life cycle of thread. It is shown in figure 4.5. It is also discussed previously that
various methods may be invoked by threads depending on their state. If a thread
tries to invoke a method which cannot be handled in the current state of that
thread, IllegalThreadStateException is thrown.
Example 1: A sleeping thread cannot receive any instructions. So it cannot
deal with a method like resume( ).
Example 2: A blocked thread cannot handle suspend( ) method.

InterruptedException is thrown when a sleeping or waiting thread is


interrupted.

Various other exceptions related to threads are ThreadDeath,


IllegalArgumentException etc.

4.2.4 Thread Priority


As at a particular instance of time, there may be multiple threads in the
system, we may assign priorities to the threads.
In a multithreading environment, there may be multiple threads which are
runnable. In such situation the priorities of the threads help in selecting the
threads for running. If multiple runnable threads have same priority, the threads
are selected on First Come First Serve basis.
We may assign a priority to a thread by using setPriority( ) method of
thread. The syntax of this method is as follows
threadname.setPriority(intvalue);
Here intvalue is an integer value. This value may be set with the help of
different priority constants available with Thread class. Different priority
constants of thread class are:
MIN_PRIORITY = 1
NORM_PRIORITY = 5 (This is default priority of every thread)
MAX_PRIORITY = 10
Generally priority of Thread.NORM_PRIORITY ± 1 is assigned to user-
defined threads. Background threads must be assigned with priority near to
MIN_PRIORITY. A programmer must take utmost care while assigning priorities
to threads.
Thread class also supports a getPriority( ) method which returns current
priority value of the thread.
When a high priority thread enters in runnable state while a low priority
thread is in running state, the running thread gets preempted. i.e. the low priority
running threads stops its execution by entering runnable state and the new high
priority thread starts its running by entering running state. This concept is called
preemption. An example program showing preemption is shown below.

Example:
class Thread1 extends Thread
{
public void run( )
{
int i;
for(i=0;i<10;i++)
{
System.out.println(“In thread 1, i = ” +i);
}
System.out.println(“Exiting Thread 1”);
}
}

class Thread2 extends Thread


{
public void run( )
{
int j;
for(j=0;j<10;j++)
{
System.out.println(“In thread 2, j = ”+j);
}
System.out.println(“Exiting Thread 2”);
}
}

class Thread3 extends Thread


{
public void run( )
{
int k;
for(k=0;k<10;k++)
{
System.out.println(“In thread 3, k = ”+k);
}
System.out.println(“Exiting Thread 3”);
}
}

class Unit4_12
{
public static void main(String[] args)
{
Thread1 t1 = new Thread1( );
Thread2 t2 = new Thread2( );
Thread3 t3 = new Thread3( );

t1.setPriority(Thread.NORM_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(Thread.MIN_PRIORITY);

System.out.println(“Started Thread 1”);


t1.start( );
System.out.println(“Started Thread 2”);
t2.start( );
System.out.println(“Started Thread 3”);
t3.start( );

System.out.println(“Exiting main thread”);


}
}

Sample Output: (May change even on multiple execution)


Started Thread 1
Started Thread 2
Started Thread 3
In thread 1, i = 0
Exiting main thread
In thread 2, j = 0
In thread 2, j = 1
In thread 1, i = 1
In thread 1, i = 2
In thread 1, i = 3
In thread 1, i = 4
In thread 3, k = 0
In thread 3, k = 1
In thread 2, j = 2
In thread 3, k = 2
In thread 1, i = 5
In thread 3, k = 3
In thread 2, j = 3
In thread 2, j = 4
In thread 2, j = 5
In thread 2, j = 6
In thread 2, j = 7
In thread 2, j = 8
In thread 1, i = 6
In thread 3, k = 4
In thread 2, j = 9
In thread 3, k = 5
In thread 1, i = 7
In thread 3, k = 6
Exiting Thread 2
In thread 3, k = 7
In thread 1, i = 8
In thread 3, k = 8
In thread 1, i = 9
In thread 3, k = 9
Exiting Thread 1
Exiting Thread 3

4.2.5 Synchronization
System may have multiple threads. Such threads may require
communicating with each other. In such case, if the communicating threads are
not synchronized, strange results may be produced. i.e. it may happen that the
shared method may get called by different threads at the same time. To avoid this,
the method may be marked keyword synchronized as,
synchronized returntype methodname(arglist)
{
----
}
Because of this, java creates a monitor. This monitor allows a thread calling
this method first time to execute that method. No any other thread is able to enter
this method as long as first thread is executing this method.

4.2.6 Deadlock
If thread 1 is accessing method1( ) & wants to access method2( ), and the
same time thread 2 is accessing method2( ) & wants to access method1( ), this
situation is called deadlock.

4.2.7 Inter-thread Communication


It involves exchange of messages between two or more threads. Java
achieves inter-thread communication with the help of various methods like notify(
), notifyall( ), wait( ) etc.

notify( )
It resumes the first thread that went to sleep mode. Its syntax is as follows
final void notify( )
notifyall( )
It resumes all the threads those are in sleep mode. Its syntax is as follows
final void notifyall( )
wait( )
It sends the calling thread into sleep mode. This thread can come out of
sleep mode only by notify( ) method or notifyall( ) method. Its syntax is as follows
final void wait( )
Sample Questions:
1. Define error. List types of errors. [2M]
2. Name any four built in Exceptions in Java. [2M]
3. Define exception. State built-in exceptions. [4M]
4. Enlist any 4 keywords used for exception handling in Java. [2M]
5. Write the syntax of try-catch-finally blocks. [2M]
6. Describe types of Errors and Exceptions in details. [6M]
7. Write a program to input name and salary of employee and throw user
defined exception if entered salary is negative. [6M]
8. Explain the two ways of creating threads in Java. [4M]
9. Describe life cycle of thread with suitable diagram. [4M]
10. Describe methods of creating a thread with example. [4M]
11. Write a program to create two threads one thread will print even numbers
from 1 to 50 and other will print odd numbers between 1 and 50. [6M]
12. Write a program to create two threads. One thread will display the
numbers from 1 to 50 (ascending order) and other thread will display
numbers from 50 to 1 (descending order). [6M]
13. Write a program to define two threads for displaying even and odd numbers
respectively with a delay of 500 ms after each number. [6M]

You might also like