0% found this document useful (0 votes)
6 views25 pages

UNIT-4 c-20

This document covers exception handling and multi-threaded programming in Java, detailing the sources of errors, types of exceptions (checked, unchecked, and errors), and the importance of exception handling mechanisms like try, catch, finally, throw, and throws. It also explains multi-threading concepts, advantages, and the life cycle of threads, including their various states. Additionally, built-in exceptions and sample programs illustrating exception handling techniques are provided.

Uploaded by

cmohandas532
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)
6 views25 pages

UNIT-4 c-20

This document covers exception handling and multi-threaded programming in Java, detailing the sources of errors, types of exceptions (checked, unchecked, and errors), and the importance of exception handling mechanisms like try, catch, finally, throw, and throws. It also explains multi-threading concepts, advantages, and the life cycle of threads, including their various states. Additionally, built-in exceptions and sample programs illustrating exception handling techniques are provided.

Uploaded by

cmohandas532
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

UNIT-4

EXCEPTION HANDLING AND MULTI-THREADED PROGRAMMING

4.1 Describe source of errors:

Source of errors: Errors are the wrongs that can make a program wrong. Errors may be classified into 2
categories:-
i) Compile time errors
ii) Run time errors
iii) Logical Errors
compile time errors:
 These are syntactical errors found in the code, due to which a program fails to compile.
 Whenever the compiler displays errors, it will not create the .class file. It is necessary that we correct all
the errors before we can successfully compile and run program.
The most common compile time errors are:
 Missing semicolons
 Missing (or) mismatch brackets in classes and methods
 Misspelling of identifiers and keywords
 Missing double codes in strings
 Use of undeclared variables
 Incompatible type in assignments (or) initialization
 Use of equal to in place of double equal to operator etc.
run time errors: These errors represent inefficiency of the computer system to execute a particular
statement. Sometimes a program may compile successfully creating the .class file but may not run properly.
Run-time errors are not detected by the Java compiler. They are detected by the JVM, only at run-time.

Most common run time errors are:

 Dividing an integer by zero


 Accessing an element i.e. out of the bounds of an array
 Trying to store a value into an array of incompatible class or type
 Passing a parameter i.e. is not in a valid range (or) value for a method.
 Trying to illegally change the state of thread.
 Attempting to use a negative size for an array.
 Converting invalid string to a number
 Accessing a character i.e. out of bounds of string
logical errors: These errors explain flaws in the logic of the program.
e.g.: 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. The programmer himself is responsible for them.

4.2 Write the Advantages Of Exceptions:


1. Separating error handling code from regular code.
2. It prevents the program for automatic termination.
3. Grouping error types and error differentiation.
4.3 Explain type of exceptions checked and unchecked: There are mainly two types of exceptions: checked
and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are
1
three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception 3. Error
1) Checked Exception: The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions
are checked at compile-time.
2) Unchecked Exception: The classes that inherit the Runtime Exception are known as unchecked exceptions.
For example, ArithmeticException, NullPointerException,ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error: Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.

4.4 write sample programs to make use of Try,Catch,Finally,Throw,Throws:

EXCEPTION: An exception is a run time error in the program.


EXCEPTION HANDLING: When, the java interpreter encounters an error such as dividing an integer
by zero, it creates an exception object and throws it i.e. informs an error has occurred.
If the exception object is not caught and handle properly, the interpreter will display an error
message. If we want the program to continue with the execution of the program to continue with the
remaining then we should try to catch the exception object thrown by the error condition and then display
an appropriate message for taking corrective action. This task is known as exception handling.
Java exception handling is managed by using the keywords. Those are
1. Try
2. Catch
3. Throw
4. Throws
5. Finally
2
TRY AND CATCH KEYWORDS:
try block: The programmer should observe the statements in his program, where there may be a
possibility of exceptions. Such statements should be written inside a try block.
Syntax: try
{

//statements
}

When JVM understands that there is an exception, in the try block, then it stores the exception details in
an exception stack and then jumps into a catch block.

catch block: Immediately following the try block includes catch where we should display the exception
details to the user.
Syntax:
catch (ExceptionType variable)
{

// stmts to be displayed when exception occurred


}

A try block and its catch statement form a unit. Remember that every try statement should be followed by at
least one catch statement otherwise compile time error will occur.

finally:
Finally creates a block of code that will be executed after a try/catch block has completed and before the
code following the try/catch block. Cleanup operations code is written inside the „finally‟ block.
The finally block will be executed whether or not an exception is thrown. The finally clause is
optional. Syntax:
finally
{

//Block of statements which releases the resources;


}

EXAMPLE: The following program includes a try block and a catch block which process the Arithmetic
Exception generated by the division by zero error.
class A
{

public static void main (String args[])


{

int
d=0;
try
{

int a=42/d;
3
[Link](“not
printed”);
}
catch (ArithmeticException e )
{

[Link](“division by zero not possible”);


[Link](“after try/catch block”);
}
finally
{
[Link](“Iam a finally block”);
}
}
}
Output:
division by zero not possible
after try/catch block
Iam a finally block

throw:
In general, we are catching exceptions that are thrown by java runtime system. However, is possible for our
program throw an exception explicitly, using the throw statement.

The general form of throw is here


Syntax: throw throwableinstance;

Here, throwable instance must be an object of type Throwable class


Ex: in the following program, we are creating an object of NullPointerException class and throwing it out of
try block as shown here:
Example: throw new NullPointerException(“exception data”);
In the above statement NullPointerException class is created and „exception data‟ is stored into its
object. Then it is thrown using throw statement now, we can catch it using catch block as,

catch(NullPointerException ne)
{

Example:

public class TestThrow1 {


//function to check if person is eligible to vote or not
4
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
[Link]("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
[Link]("rest of the code...");
}
}

Output:

throws:
A throws clause lists the types of exception that a method may throw. All exception that a method can throw
must be declared in the throws clause.
The general form at a method declaration that includes a throws clause is
Syntax:
type method_name(parameters list) throws Exception list
{

Body of method;
}

Here, Exception list is a comma separated list of the exceptions that a method can throws.
import [Link].*;
class M{
void method()throws IOException{
[Link]("device operation performed");

5
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
[Link]();

[Link]("normal flow...");
}
}

Output:

device operation performed


normal flow...

4.5: Explain The Concept Of Multi-Catch Statements Programs:


Multi catch statements:

Most of the times there is possibility of more than one exception present in the program. In this case, the
programmer should write multiple catch blocks to handle each one of them.

In this program, there are 2 – exceptions ArithmenticException and ArrayIndexOutOfBound exception. These
exceptions are handled with the help of 2 catch blocks.
Example:
class edemo {
public static void main (String [] args)
{

try
{

int n=[Link];
[Link]("n="
+n); int a=45/n;
[Link] ("DIVISION VALUE = "+a);
int b[]={10,20,30};
b[50]=100;
}

catch(ArithmeticException Ae)
{

[Link](Ae);
[Link] ("DONT ENTER ZERO FOR DENOMINATOR...");
}

6
catch(ArrayIndexOutOfBoundsException A)
{

[Link](A);
[Link] ("ARRAY INDEX IS OUT OF RANGE..");
}

finally
{

[Link] ("I AM FROM FINALLY...");


}

Note: even if there is scope of multiple exceptions, only one exception at a time will occur.
4.6:Explain how to write nested try in exception handling with example:
The try statement can be nested. That is, a try statement can be inside the block of another try. There could
be situations where there is possibility of generation of multiple exceptions of different types with in a particular
block of the program code. We can use nested try statements in such situations. The execution of the corresponding
catch blocks of nested try statements is done using a stack.
Syntax:
try
{

statement 1;
statemen2;
try
{

statement 1;
statement 2;
}

catch(Exception e)
{

catch(Exception e)
{

....

When nested try blocks are used, the inner try block is executed first. Any exception thrown in the inner try block is
7
caught in the corresponding catch block. If a matching catch block is not found, then catch block of the outer try
block are inspected until all nested try statements are exhausted. If no matching blocks are found, the Java Runtime
Environment handles the execution.

public class NestedTryBlock{


public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
[Link]("going to divide by 0");
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
[Link](e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)
{
[Link]("handled the exception (outer catch)");
}

[Link]("normal flow..");
}
8
}

Output:

4.7 Describe Built-in Exceptions:

Built-in Exceptions are the exceptions which are already available in Java. These exceptions are suitable to explain
certain error situations. lists the important Built-in Exceptions.

Exception class Meaning


ArithmeticException Thrown when an exceptional condition has occurred in an
arithmetic operation.
ArrayIndexOutOfBoundException Thrown to indicate that an array has been accessed with an
illegal index. The index is either negative or greater than or
equal to the size of the array.
ClassNotFoundException This exception is raised when we try to access a class whose
definition is not found.
FileNotFoundException Raised when a file is not accessible or does not open.
IOException Thrown when an input-output operation failed or
interrupted.
InterruptedException Thrown when a thread is waiting, sleeping, or doing some
processing, and it is interrupted.
NoSuchFieldException Thrown when a class does not contain the field for (or
variable) specified.
NoSuchMethodException Thrown when accessing a method which is not found.
NullPointerException Raised when referring to the members of a null object, null
represents nothing.

NumberFormatException Raised when a method could not convert a string into a


numeric format.
RuntimeException This represents any exception which occurs during runtime.
StringIndexOutOfBoundsException Thrown by String class methods to indicate that an index is
either negative or greater than the size of the string.
Example Refer the 4.4 topic example program.

4.8 Describe multithreading:


Thread:- Threads are light-weighted processes. A thread represents a separate path of
executi
on of a group of statements.
9
Uses of threads: - Thread can be used for multiple purposes.

1) Threads are mainly used in server-side programs to serve the needs of multiple clients on a network (or) internet.
2) Threads are also used to create games &animation. Animation means moving the objects from one place to
another. In many games, generally we have to perform more than one task simultaneously. There threads will be of
invaluable help.

Multithreading is a process of executing multiple threads simultaneously.


A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing andmultithreading,
both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory [Link] don't
allocate separate memory area so saves memory, and context-switching between the threads takes less time
than process. 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.

4.9 Explain thread life -cycle and states:


A thread is a path of execution in a program that enters any one of the following five states during its life cycle.
The five states are as follows:
1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead

Following are the stages of the life cycle –


1. Newborn State: When a thread object is created a new thread is born and said to be in Newborn state.

2. Runnable State: If a thread is in this state it means that the thread is ready for execution and waiting for

10
the availability of the processor. If all threads in queue are of same priority then they are given time slots for
execution in round robin fashion.

[Link] State: It means that the processor has given its time to the thread for execution. A thread
keeps running until the following conditions occur.
a. Thread give up its control on its own and it can happen in the following situations.
 A thread gets suspended using suspend () method which can only berevived with resume()method.
 A thread is made to sleep for a specified period of time using sleep(time) method, where time in
milliseconds.
 A thread is made to wait for some event to occur using wait () method. In this case a thread can be
scheduled to run again using notify()method.
b. A thread is pre-empted by a higher priority thread.
4. Blocked State: If a thread is prevented from entering into runnable state
and Sub-sequently running state, then a thread is said to be in Blocked state.
5. Dead State: A runnable thread enters the Dead or terminated state when it completes its task or
otherwise terminates.
Thread methods:
 currentThread ():Returns a reference to the currently executing thread object.
 yield ():Causes the runtime to context switch from current thread to next available thread.
 sleep (int n):Current thread sleeps for n milliseconds.
 start (): Used to start a thread. Run () will be called
 run (): It is the body of the running thread to be overridden.
 stop () : Causes the thread to stop immediately.
 setName(string name):Sets the name for the current thread.
 getName():Returns the name of the current thread
 activeCount():Returns the no of active threads in the current threads groups.
 getThreadGroup():Returns the thread group to which this thread belongs.
 getState():Returns the state of the thread
 getPriority():obtains a thread ‘s priority.
 isAlive():determine if a thread is still running.
 join():wait for a thread to terminate.

4.10 Explain how to create single thread with example program:


Create thread using Thread Class
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 thread in a program; the following steps should be used. Java defines 2-ways to create thread.
1) We can implement the Runnable interface.
2) We can extend the 'Thread' class
itself. Steps to create threads:
We can make our class runnable as thread by extending the class [Link]. This gives us access to
all the thread methods directly. It includes the following steps:
1. Create the MyClass that extending the Thread class.
2. Implement the run() method that is responsible for executing the sequence of code that the thread will execute.
3. Create an object to MyClass so that the run () method is available for execution.
4. Finally Run the Thread by the start( ) method to initiate the thread execution

11
Now, the thread will start execution the object of MyClass. In that object, run() method is found, hence it will
execute the statements inside that run() method.
Single thread:
//creating a thread and running it by extending the Thread class
class MyThread extends Thread //step1
{

public void run( ) //step2


{

for(int i=1;i<=100;i++)
{

[Link](i);
}

class ThreadDemo
{

public static void main(String args[])


{

MyThread obj=new MyThread();//step3


[Link](); //step4
}

}
Create Thread using Runnable interface
By Implementing Runnable interface:
Easiest way to create a thread is to create class that implements “Runnable” interface which abstracts a unit
of executable code. Then constructs a thread or any object that implements the Runnable.
It includes the following steps to create thread that implements Runnable interface:
1. Create the MyClass that extending the Thread class.
2. Implement the run() method that is responsible for executing the sequence of code that the thread will execute.
3. Create an object to MyClass so that the run () method is available for execution.
4. Now create a thread & attach the thread to the object.
5. Finally Run the Thread by the start( ) method to initiate the thread execution.

//creating a thread and running it by implementing the Runnable interface class MyThread
implements Runnable //step1
{

public void run() //step2


{

for(int i=1;i<=100;i++)
{

[Link](i);
}

}
12
}

class ThreadDemo2
{

public static void main(String args[])


{

MyThread obj=new MyThread();//step3


Thread t1=new Thread(obj);//step4
[Link]();//step5
}

class ThreadDemo
{

public static void main(String args[])


{

MyThread obj=new MyThread();//step3 [Link](); //step4


}

4.11 Explain how to create Multi thread with example program:


Create Multiple Threads
We have been using only two threads: The main thread and the child thread. However, our program can create as
many threads as it needs. It is implemented in the below program.
Example1:
class A extends Thread
{

public void run()


{
[Link](“thread is
started”); for(int i=1;i<=4;i++)
{

[Link](“from thread A: i=”+i);


}

[Link](“exit from A”);


}

class B extends Thread


{

public void run()

13
{

[Link](“thread B
started”); for (int j=1;j<=4;j++)
{

[Link](“from thread B:j=”+j);


}

[Link](“exist from B”);


}

class MultipleThreads
{

public static void main(String args[])


{

A obj1 =new A();


B obj2=new B();
[Link]();
[Link]();
}

4.12 Illustrate thread priorities in multiple thread with example:

When the threads are created & started a 'thread- scheduler' program in JVM will load them into memory &
execute them. This scheduler will allot more JVM time to those threads which are having higher priorities. The
threads of the same priority are given equal treatment by the java scheduler and, therefore, execute on a FCFS basis.

The priority number of a thread will change from 1to 10.


The minimum priority i.e, Thread. MIN_PRIORITY of a thread is 1.

The maximum priority i.e,Thread. MAX_PRIORITY of a thread is 10.

The normal priority (or)default priority i.e, Thread. NORM_PRIORITY of a thread is 5.

To set a thread's priority, use the setPriority () method, which is a member of Thread. The general form is.

final void setPriority (int number);

To get the current priority of a thread, use the getPriority () method of Thread class.
final int getPriority();

Example program:

14
class A extends Thread
{

public void run()


{
[Link](“threadA is
started”); for(int i=1;i<=4;i++)
{

[Link](“from thread A: i=”+i);


}

[Link](“exit from A”);


}

class B extends Thread


{

public void run()


{

[Link](“thread B
started”); for (int j=1;j<=4;j++)
{

[Link](“from thread B:j=”+j);


}

[Link](“exist from B”);

class c extends Thread


{

public void run()


{
[Link](“thread c is started”);
for(int k=1;k<=4;k++)
{

[Link](“from thread c: k=”+k);


}

[Link](“exit from c”);


}

}
15
class MultipleThreads
{

public static void main(String args[])


{

A obj1 =new A();


B obj2=new B();

C obj1 =new C();


[Link](Thread.MAX_PRIORITY);

[Link]([Link]()+1);

[Link](Thread.MIN_PRIORITY);

[Link](“start A “);

[Link]();

[Link](“start B “);

[Link]();

[Link](“start c “);

[Link]();

[Link](“End of main thread“);

Output:

start A

start B

start C

thread B is started

from thread B:j=1

from thread B:j=2

thread c is started

from thread c:k=1;

from thread c:k=2;

from thread c:k=3;


16
from thread c:k=4;

Exit form c

End of main thread

from thread B:j=3

from thread B:j=4

Exit form B

thread A is started

from thread A: i= 1;

from thread A: i= 2;

from thread A: i= 3;

from thread A: i= 4;

Exit form A

4.13: DESCRIBE THE CONCEPT OF SYNCHRONIZATION WITH EXAMPLE PROGRAM:-

What is 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 object is like a locked object, locked on a thread. It is a room with only one door. A person has
entered the room & locked from it. The second person who wants to enter the room should wait till the first
person came out.
 A thread also locks the object after entering it. Then the next thread can't enter it till the first thread comes out.
This means the object is locked mutually on threads. So, this object is called 'mutex'(mutually exclusive lock).

t1 t2—wait till the t1 comes out

mutex

Fig: Thread synchronization

How can we synchronize the object? There are 2-ways of doing this.
1) Using synchronized block: -Here, we can embed a group of statements of the object (inside run () method) within
17
a synchronized block, as shown here:
synchronized (object)

//statements;

The statements inside the synchronized block are all available to only one thread at a time. They are not available to
more than one thread simultaneously.
2) Using synchronized keyword:- we can synchronize an entire method by using synchronized keyword. For e g:- if
we went to synchronize the code of display() method, then add the synchronized keyword before the method as show
here.
synchronized void display()

//statements;

Diff b/w synchronized block, synchronized keyword:


Synchronized block is useful to synchronize a block of statements. Synchronized keyword is useful to synchronize an
entire method.
//java program to synchronize the threads acting on the same object. class Reserve
implements Runnable
{

int available=1; int wanted;


Reserve(int i)
{

wanted=i;
}

public void run()


{

synchronized(this)
{

[Link]("Available berths="+available);
if(available>=wanted)
{

String name=[Link]().getName();
[Link](wanted+"berths reserved for"+name); try
{

[Link](1500); available=available-
wanted;
}

18
catch(InterruptedException ie)
{

else
[Link]("sorry no berths");
}

class ThreadSynch

public static void main(String x[])


{

Reserve obj=new Reserve(1); Thread t1=new


Thread(obj); Thread t2=new Thread(obj);
[Link]("first passenger"); [Link]("second
passenger"); [Link]();
[Link]();
}

Output:

4.14 EXPLAIN INTER THREAD COMMUNICATION WITH EXAMPLE PROGRAM:

In some cases, 2 or more threads should communicate with each other. For example consider the classic
queuing problem, where one thread is producing some data and another is consuming it.
Here, polling is usually implemented by a loop that is used to check some condition repeatedly. Once the condition is
true, appropriate action is taken. This wastes CPU time.
In polling the producer has to wait until the consumer is finished before it generates more data. The
19
consumer would waste many CPU cycles while it waited for the producer to produce. Once the producer was finished,
it would start polling wasting more CPU cycles waiting for the consumer to finish, and so on.
In this way, the producer and consumer can communicate with each other. But this is not an efficient way of
communication. To avoid polling, java includes an elegant inter-process communication mechanism via
wait(),notify(),notifyAll() methods.

1. [Link]():- this method releases an object and sends a notification to a waiting thread that the object is
available.
2. [Link]():- this method is useful to send notifications to all waiting threads that the object is available.
3. [Link]():- this method makes a thread wait for the object till it receives a notification from notify() or
notifyAll() methods.
Note: these methods are used inside the synchronized blocks
Example:

class Buffer{
int a;
boolean produced = false;

public synchronized void produce(int x){


if(produced){
[Link]("Producer is waiting...");
try{
wait();
}catch(Exception e){
[Link](e);
}
}
a=x;
[Link]("Product" + a + " is produced.");
produced = true;
notify();
}

public synchronized void consume(){


if(!produced){
[Link]("Consumer is waiting...");
try{
wait();
}catch(Exception e){
[Link](e);
}
}
[Link]("Product" + a + " is consumed.");
produced = false;
notify();
}
}

class Producer extends Thread{


Buffer b;
20
public Producer(Buffer b){
this.b = b;
}

public void run(){


[Link]("Producer start producing...");
for(int i = 1; i <= 3; i++){
[Link](i);
}
}
}

class Consumer extends Thread{


Buffer b;
public Consumer(Buffer b){
this.b = b;
}

public void run(){


[Link]("Consumer start consuming...");
for(int i = 1; i <= 3; i++){
[Link]();
}
}
}

public class ProducerConsumerExample {


public static void main(String args[]){
//Create Buffer object.
Buffer b = new Buffer();

//creating producer thread.


Producer p = new Producer(b);

//creating consumer thread.


Consumer c = new Consumer(b);

//starting threads.
[Link]();
[Link]();
}
}

0utput:
Consumer start consuming...
Producer start producing...
Consumer is waiting...
Product1 is produced.
Producer is waiting...
Product1 is consumed.
Consumer is waiting...
21
Product2 is produced.
Producer is waiting...
Product2 is consumed.
Consumer is waiting...
Product3 is produced.
Producer is waiting...
Product3 is consumed.
Consumer is waiting...

4.15 EXPALIN DEAD LOCK:


Thread dead lock: deadlock occurs when 2-threads have a circular dependency on a pair of
synchronized [Link] is, when a thread has locked on object & waiting for another object to be
released by another thread, and the other thread is also waiting for the first thread to release the first
object, both the threads will continue waiting forever.

import [Link].*;
class BookTicket extends Thread
{

Object train,comp;
BookTicket(Object train,Object comp)
{

[Link]=train;
[Link]=comp;
}

public void run()


{

synchronized(train)
{

[Link]("bookticket is locked by
train"); try
{

[Link](150);
}

catch(InterruptedException e)
{
}
[Link]("bookticket is waiting to lock on compartment");
synchronized(comp)
{

[Link]("bookticket locked on compartment");


}

22
}

class CancelTicket extends Thread


{

Object train,comp;
CancelTicket(Object comp ,Object train )
{

[Link]=comp;
[Link]=train;
}

public void run()


{
synchronized(comp)
{

[Link]("cancel ticket locked on compartment");


try
{

[Link](200);
}

catch(InterruptedException e)
{
}
[Link]("cancel ticket waiting for train ticket object to lock");
synchronized(train)
{

[Link]("cancel ticket locked on train");


}

}}}

class ThreadDeadlock

public static void main(String arg[])


{

Object train = new Object(); Object comp =


new Object();
23
BookTicket obj1 = new BookTicket(train,comp); CancelTicket obj2
= new CancelTicket(comp,train); Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2); [Link]();
[Link]();
}}

Extra sample program:


class MyThread extends Thread {
public void run()
{
try
{
for(int i=1;i<=5;i++) [Link]([Link]().getName()+":"+i);
[Link](2000);
}
catch(InterruptedException e)
{
[Link]([Link]().getName()+"interrupted.");
}
[Link]([Link]().getName()+"exiting.");
}
}

class ThreadResume{

public static void main(String x[]){

MyThread obj1=new MyThread();


MyThread obj2=new MyThread();
Thread t1=new Thread(obj1,"one");
Thread t2=new Thread(obj2,"two");
[Link]();
[Link]();
[Link](" thread one is
alive:"+[Link]()); [Link](" thread
two is alive:"+[Link]()); try
{

[Link](100);
[Link]();
[Link]("suspending
thread:"+[Link]()); [Link](100);
[Link]();
[Link]("resuming thread
one"); [Link](100);
[Link]();
[Link]("suspending
thread:"+[Link]()); [Link](100);
[Link]();
[Link]("resuming thread two");

24
}
catch(InterruptedException ie)
{

[Link]("main thread interrupted.");


}

tr
y
{
[Link]("Waiting for threads to finish:");
[Link]();
[Link]();
[Link](" thread one is alive:"+[Link]());
[Link](" thread two is alive:"+[Link]());

catch(InterruptedException ie)
{

[Link]("main thread interrupted.");


}

[Link]("main thread exiting");


}
}

Output:

-----------------------------------PREPARED BY [Link]------------------------------------

25

You might also like