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

Exception Handling and Multithreading

The document discusses exception handling in Java. It defines different types of errors like compile time errors and runtime errors. It explains concepts like try, catch, throw, throws and finally blocks used in exception handling and provides examples to demonstrate their usage.

Uploaded by

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

Exception Handling and Multithreading

The document discusses exception handling in Java. It defines different types of errors like compile time errors and runtime errors. It explains concepts like try, catch, throw, throws and finally blocks used in exception handling and provides examples to demonstrate their usage.

Uploaded by

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

EXCEPTION HANDLING Java Programming

AND MULTITHREADING
EXCEPTION HANDLING AND MULTITHREADING

1) State and explain types of errors in java?


(Summer 18) 4 marks
Types of Error
a) Compile Time Errors:
All syntax errors given by Java Compiler are called compile
time errors. When program is compiled, java checks the
syntax of each statement. If any syntax error occurs, it will be
displayed to user, and .class file will not be created.

Common compile time Errors


I. Missing semicolon
II. Missing of brackets in classes and methods
III. Misspelling of variables and keywords.
IV. Missing double quotes in Strings.
V. Use of undeclared variable.
VI. Incompatible type of assignment/initialization.
VII. Bad reference to object.

b) Run time error:


After creating .class file, Errors which are generated, while
program is running are known as runtime errors. Results in
termination of program.

Common runtime Errors


I. Dividing an integer by zero.
II. Accessing an element that is out of the bounds of an
array.
III. Trying to store data at negative index value.
IV. Opening file which does not exist.
V. Converting invalid string to a number.

2) Define an exception. How it is handled?


(Summer 15, Winter 15 and Winter 16) 4 marks
Exception: An exception is an event, which occurs during the
execution of a program, that stop the flow of the program's
instructions and takes appropriate actions if handled.
EXCEPTION HANDLING AND MULTITHREADING

a) try: This block applies a monitor on the statements written


inside it. If there exist any exception, the control is
transferred to catch or finally block
b) catch: This block includes the actions to be taken if a
particular exception occurs.
c) finally: finally block includes the statements which are to be
executed in any case, in case the exception is raised or not.
d) throw: This keyword is generally used in case of user
defined exception, to forcefully raise the exception and take
the required action.
e) throws: throws keyword can be used along with the method
definition to name the list of exceptions which are likely to
happen during the execution of that method. In that case, try
… catch block is not necessary in the code.

3) What is exception? Why the exception occurred in program?


Explain with suitable example. (Winter 17) 8 marks
An exception is an event, which occurs during the execution of a
program on an existence of an error, generally a run time error. If
there are some syntactical errors in the program, those can be
caught and debugged by compiler, but if there exist any logical
errors, the program may get terminated at run time.
Exception handling mechanism helps no to terminate the program
at runtime because of logical error, but it allows the program to
take some proper action and execute further.
It is achieved by 5 keywords as try, catch, throw, throws and
finally.
a) try: The code which is to be monitored is contained in try
block
b) catch: If there exists any error in try block it is caught in
catch block and action is taken. It works like a method and
accepts an argument in the form, of Exception object.
EXCEPTION HANDLING AND MULTITHREADING

c) throw: It is mainly used to throw an instance of user defined


exception.
Example:
throw new myException(“Invalid number”);
assuming myException as a user defined exception
d) throws: It can be used with the method’s declaration which
may have some run time errors.
Example:
public static void main(String args[]) throws IOException
e) finally: it includes the code which executes irrespective of
errors in try block. A try should have at least one catch or a
finally block associated to complete the syntax.

Example (Program to raise an exception if the


passwords do not match)
import java.io.*;
classPasswordException extends Exception
{
PasswordException(String msg)
{
super(msg);
}
}
class PassCheck
{
public static void main(String args[]) throws IOException
{
BufferedReader bin=new BufferedReader(new
InputStreamReader(System.in));
try
{
EXCEPTION HANDLING AND MULTITHREADING

System.out.println("Enter Password : ");


if(bin.readLine().equals("abc123"))
{
System.out.println("Authenticated ");
}
Else
{
throw new PasswordException("Authentication failure");
}
}
catch(PasswordException e)
{
System.out.println(e);
}
}
}

4) With syntax and example explain try & catch statement.


(Summer 18) 4 marks
try- Program statements that you want to monitor for exceptions
are contained within a try block. If an exception occurs within the
try block, it is thrown.
Syntax: try
{
// block of code to monitor for errors
}

catch- Your code can catch this exception (using catch) and
handle it in some rational manner. System-generated exceptions
are automatically thrown by the Java runtime system. A catch
block immediately follows the try block. The catch block can have
one or more statements that are necessary to process the
exception.
Syntax: catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
E.g.
EXCEPTION HANDLING AND MULTITHREADING

class DemoException {
public static void main(String args[])
{
try
{
int b=8;
int c=b/0;
System.out.println("Answer="+c);
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero");
}}}

5) Describe use of “throws” with suitable example.


(Summer 16) 4 marks
Throws clause
If a method is capable of causing an exception that it does not
handle, it must specify this behavior so that callers of the method
can guard themselves against that exception. You do this by
including a „throws‟ clause in the methods declaration. A throws
clause lists the types of exception that a method might throw.
General form of method declaration that includes „throws‟ clause
Type method-name (parameter list) throws exception list {// body
of method} Here exception list can be separated by a comma.

Eg.
class XYZ
{
XYZ();
{
// Constructer definition
}
void show() throws Exception
{
throw new Exception()
}
}
EXCEPTION HANDLING AND MULTITHREADING

6) Define throws & finally statements with its syntax and


example. (Summer 18) 4 marks
a) throws statement: throws keyword is used to declare that a
method may throw one or some exceptions. The caller must
catch the exceptions.
Example:
import java.io.*;
class file1
{
public static void main(String[] args) throws IOException
{
FileWriter file = new FileWriter("Data1.txt");
file.write("These are contents of my file");
file.close();
}
}

b) finally statement: finally block is a block that is used to


execute important code such as closing connection, stream
etc. Java finally block is always executed whether exception
is handled or not. Java finally block follows try or catch block.
Example :
import java.io.*;
class file1
{
public static void main(String[] args)
{
try
{
FileWriter file = new FileWriter("c:\\Data1.txt");
file.write("Hello");
}
catch(IOException)
{}
finally
{
file.close();
}
EXCEPTION HANDLING AND MULTITHREADING

}
}

7) Explain the following clause w.r.t. exception handling:


(i) try
(ii) catch
(iii) throw
(iv) finally
(Winter 15) 4 marks
a) try- Program statements that you want to monitor for
exceptions are contained within a try block. If an exception
occurs within the try block, it is thrown.
Syntax:
try
{
// block of code to monitor for errors
}
b) catch- Your code can catch this exception (using catch) and
handle it in some rational manner. System-generated
exceptions are automatically thrown by the Java runtime
system. A catch block immediately follows the try block. The
catch block too can have one or more statements that are
necessary to process the exception.
Syntax:
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
c) throw:It is possible for a program to throw an exception
explicitly, using the throw statement.
The general form of throw is:

throw new ThrowableInstance;


or
throw Throwableinstance;

throw statement explicitly throws an built-in /user- defined


exception. When throw statement is executed, the flow of
EXCEPTION HANDLING AND MULTITHREADING

execution stops immediately after throw statement, and any


subsequent statements are not executed.

d) finally: It can be used to handle an exception which is not


caught by any of the previous catch statements. finally block
can be used to handle any statement generated by try block.
It may be added immediately after try or after last catch
block.
Syntax:
finally
{
// block of code to be executed before try block ends
}

8) What is the use of try catch and finally statement give


example? (Winter 17) 4 marks
a) try- Program statements that you want to monitor for
exceptions are contained within a try block. If an exception
occurs within the try block, it is thrown.
Syntax:
try
{
// block of code to monitor for errors
}
For eg. try
{
for(inti = 1;i <= 10;i+=2)
{
System.out.println("Odd Thread : "+i);
Thread.sleep(1500);
}
}

b) catch- Your code can catch this exception (using catch) and
handle it in some rational manner. System-generated
exceptions are automatically thrown by the Java runtime
system. A catch block immediately follows the try block. The
EXCEPTION HANDLING AND MULTITHREADING

catch block too can have one or more statements that are
necessary to process the exception.
Syntax:
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
For eg.
catch (InterruptedExceptione){}

c) finally: It can be used to handle an exception which is not


caught by any of the previous catch statements. finally block
can be used to handle any statement generated by try block.
It may be added immediately after try or after last catch
block.
Syntax:
finally
{
// block of code to be executed before try block ends
}
For eg.
finally{System.out.println("finally block is always executed");}

9) What is exception? WAP to accept a password from the user


and throw “Authentication Failure” exception if the password
is incorrect. (Summer 17) 8 marks
An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program execution.
It can be handled by 5 keywords in java as follows:
a) try: This block monitors the code for errors.
b) catch: This block implements the code if exception is raised
due to some error in try block.
c) throw: To throw a user define exception
d) throws: Can be used with the method’s declaration which are
may have some run time errors.
e) finally: Includes the code which executes irrespective of
errors in try block
EXCEPTION HANDLING AND MULTITHREADING

Program:
import java.io.*;
class PasswordException extends Exception
{
PasswordException(String msg)
{
super(msg);
}
}
class PassCheck
{
public static void main(String args[])
{
BufferedReader bin=new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter Password : ");
if(bin.readLine().equals("abc123"))
{
System.out.println("Authenticated ");
}
else
{
throw new PasswordException("Authentication failure");
}
}
catch(PasswordException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
EXCEPTION HANDLING AND MULTITHREADING

10) Define an exception called “No match Exception” that is


thrown when a string is not equal to “MSBTE”. Write program
(Winter 16) 8 marks
//program to create user defined Exception No Match Exception
import java.io.*;
class NoMatchException extends Exception
{
NoMatchException(String s)
{
super(s);
}
}
class test1
{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new
InputStreamReader(System.in) );
System.out.println("Enter a word:");
String str= br.readLine();
try
{
if (str.compareTo("MSBTE")!=0) // can be done with equals()
throw new NoMatchException("Strings are not equal");
else
System.out.println("Strings are equal");
}
catch(NoMatchException e)
{
System.out.println(e.getMessage());
}
}
}
EXCEPTION HANDLING AND MULTITHREADING

11) Write a program to input name and balance of customer


and thread an user defined exception if balance less than
1500. (Winter 17) 4 marks
import java.io.*;
class MyException extends Exception{
MyException(String str) {
super(str);
}
}
class AccountDetails {
public static void main(String a[]) {
try {
BufferedReaderbr = new BufferedReader(new
InputStreamReader(System.in));
String name;
int balance;
System.out.println("Enter name");
name = br.readLine();
System.out.println("Enter balance");
balance = Integer.parseInt(br.readLine());
try {
if(balance<1500) {
throw new MyException("Balance is less");
} else {
System.out.println("Everything alright");
}
} catch(MyException me) {
System.out.println("Exception caught"+me);
}
} catch(Exception e) {
System.out.println("Exception caught"+e);
}
}
}
EXCEPTION HANDLING AND MULTITHREADING

12) Write a program to create two thread one to print odd


number only and other to print even numbers.
(Winter 17) 4 marks
class EvenThread extends Thread
{
EvenThread()
{
start();
}
public void run()
{
try
{
for(inti = 0;i <= 10;i+=2)
{
System.out.println("Even Thread : "+i);
Thread.sleep(500);
}
}
catch (InterruptedExceptione){}
}
}
class OddThread implements Runnable
{
OddThread()
{
Thread t = new Thread(this);
t.start();
}
public void run()
{
try
{
for(inti = 1;i <= 10;i+=2)
{
System.out.println("Odd Thread : "+i);
Thread.sleep(1500);
}
EXCEPTION HANDLING AND MULTITHREADING

}
catch (InterruptedExceptione){}
}
}
class Print
{
public static void main(String args[])
{
new EvenThread();
new OddThread();
}
}

13) Write a program to define two thread one to print from 1


to 100 and other to print from 100 to 1. First thread transfer
control to second thread after delay of 500 ms.
(Winter 17) 8 marks
class thread1 extends Thread
{
public void run()
{
int flag=0;
for(inti=1; i<=10;i++)
{
System.out.println("thread1:"+i);
try
{
Thread.sleep(500);
flag=1;
}
catch(InterruptedException e)
{}
if (flag==1)
yield();
}
}
}
class thread2 extends Thread
EXCEPTION HANDLING AND MULTITHREADING

{
public void run()
{
int flag=0;
for(inti=10; i>=1;i--)
{
System.out.println("thread2:"+i);
try
{
Thread.sleep(500);
flag=1;
}
catch(InterruptedException e)
{}
if (flag==1)
yield();
}
}
}
class test
{
public static void main(String args[])
{
thread1 t1= new thread1();
thread2 t2= new thread2();
t1.start();
t2.start();
}
}

14) Write a program to create two threads, one to print


numbers in original order and other in reverse order from 1 to
10. (Summer 17) 8 marks
class thread1 extends Thread
{
public void run()
{
for(int i=1 ; i<=10;i++)
EXCEPTION HANDLING AND MULTITHREADING

{
System.out.println("Thread 1 :" +i);
}
}
}
class thread2 extends Thread
{
public void run()
{
for(int i=10 ; i>=1;i--)
{
System.out.println("Thread 2 :" +i);
}
}
}
class test
{
public static void main(String args[])
{
thread1 t1 = new thread1();
thread2 t2= new thread2();
t1.start();
t2.start();
}
}

15) Write a java program to implement runnable interface


with example. (Summer 18) 8 marks
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
EXCEPTION HANDLING AND MULTITHREADING

try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

16) With suitable diagram explain life cycle of thread.


(Summer 15) 8 marks
EXCEPTION HANDLING AND MULTITHREADING

Thread Life Cycle


Thread has five different states throughout its life

Newborn State
Runnable State
Running State
Blocked State
Dead State

Thread should be in any one state of above and it can be move


from one state to another by different methods and ways.

a) Newborn state: When a thread object is created it is said to be


in a new born state. When the thread is in a new born state it is
not scheduled running from this state it can be scheduled for
running by start() or killed by stop(). If put in a queue it moves to
runnable state
b) Runnable State: It means that thread is ready for execution
and is waiting for the availability of the processor i.e. the thread
has joined the queue and is waiting for execution. If all threads
have equal priority then they are given time slots for execution
in round robin fashion. The thread that relinquishes control joins
the queue at the end and again waits for its turn. A thread can
relinquish the control to another before its turn comes by yield().
c) Running State: It means that the processor has given its time
to the thread for execution. The thread runs until it relinquishes
control on its own or it is pre-empted by a higher priority thread.
d) Blocked state: A thread can be temporarily suspended or
blocked from entering into the runnable and running state by
using either of the following thread method
suspend() : Thread can be suspended by this method. It can
be rescheduled by resume().
wait(): If a thread requires to wait until some event occurs, it
can be done using wait method and can be scheduled to run
again by notify().
sleep(): We can put a thread to sleep for a specified time period
using sleep(time) where time is in ms. It reenters the runnable
state as soon as period has elapsed /over
EXCEPTION HANDLING AND MULTITHREADING

e) Dead State: Whenever we want to stop a thread form running


further we can call its stop(). The statement causes the thread
to move to a dead state. A thread will also move to dead state
automatically when it reaches to end of the method. The stop
method may be used when the premature death is required.

17) Describe life cycle of thread. (Summer 16) 4 marks


Thread Life Cycle Thread has five different states throughout its
life.
a) Newborn State
b) Runnable State
c) Running State
d) Blocked State
e) Dead State

Thread should be in any one state of above and it can be


move from one state to another by different methods and
ways

a) Newborn state: When a thread object is created it is


said to be in a new born state. When the thread is in a
new born state it is not scheduled running from this
state it can be scheduled for running by start() or killed
by stop(). If put in a queue it moves to runnable state.
b) Runnable State: It means that thread is ready for
execution and is waiting for the availability of the
processor i.e. the thread has joined the queue and is
EXCEPTION HANDLING AND MULTITHREADING

waiting for execution. If all threads have equal priority


then they are given time slots for execution in round
robin fashion. The thread that relinquishes control joins
the queue at the end and again waits for its turn. A
thread can relinquish the control to another before its
turn comes by yield().
c) Running State: It means that the processor has given
its time to the thread for execution. The thread runs
until it relinquishes control on its own or it is pre-
empted by a higher priority thread
d) Blocked state: A thread can be temporarily suspended
or blocked from entering into the runnable and running
state by using either of the following thread method
suspend() : Thread can be suspended by this method.
It can be rescheduled by resume().
wait(): If a thread requires to wait until some event
occurs, it can be done using wait method andcan be
scheduled to run again by notify().
sleep(): We can put a thread to sleep for a specified
time period using sleep(time) where time is in ms. It
reenters the runnable state as soon as period has
elapsed /over
e) Dead State: Whenever we want to stop a thread form
running further we can call its stop(). The statement
causes the thread to move to a dead state. A thread
will also move to dead state automatically when it
reaches to end of the method. The stop method may
be used when the premature death is required

18) What is thread? Draw thread life cycle diagram in Java


(Summer 17) 4 marks
A thread is a single sequential flow of control within a program.
They are lightweight processes that exist within a process. They
share the process’s resource, including memory and are more
efficient. JVM allows an application to have multiple threads of
execution running concurrently. Thread has a priority. Threads with
higher priority are executed in preference to threads with lower
priority.
EXCEPTION HANDLING AND MULTITHREADING

19) With proper syntax and example explain following


thread methods:
(1) wait( )
(2) sleep( )
(3) resume( )
(4) notify( )
(Summer 2018) 4 marks

a) wait():
syntax : public final void wait()
This method causes the current thread to wait until another
thread invokes the notify() method or the notifyAll() method
for this object.

b) sleep():
syntax: public static void sleep(long millis) throws
InterruptedException
We can put a thread to sleep for a specified time period
using sleep(time) where time is in ms. It reenters the
runnable state as soon as period has elapsed /over.

c) resume():
syntax : public void resume()
This method resumes a thread which was suspended using
suspend() method.
EXCEPTION HANDLING AND MULTITHREADING

d) notify():
syntax: public final void notify()
notify() method wakes up the first thread that called wait() on
the same object.

Eg.
class sus extends Thread implements Runnable
{
static Thread th;
float rad,r;
public sus()
{
th= new Thread();
th.start();
}
public void op()
{
System.out.println("\nThis is OP");
if(rad==0)
{
System.out.println("Waiting for input radius");
try
{
wait();
}
catch(Exception ex)
{
}
}
}
public void ip()
{
System.out.println("\nThis is IP");
r=7;
rad= r;
System.out.println(rad);
System.out.println("Area = "+3.14*rad*rad);
notify();
EXCEPTION HANDLING AND MULTITHREADING

}
public static void main(String arp[])
{
try{
sus s1 = new sus();
System.out.println("\nReady to go");
Thread.sleep(2000);
System.out.println("\nI am resuming");
th.suspend();
Thread.sleep(2000);
th.resume();
System.out.println("\nI am resumed once again");
s1.op();
s1.ip();
s1.op();
}
catch(Exception e)
{}
}
}

20) Explain thread priority and method to get and set priority
values. (Summer 15) 4 marks
Threads in java are sub programs of main application program and
share the same memory space. They are known as light weight
threads. A java program requires at least one thread called as
main thread. The main thread is actually the main method module
which is designed to create and start other threads. Thread
Priority: In java each thread is assigned a priority which affects the
order in which it is scheduled for running. Threads of same priority
are given equal treatment by the java scheduler. The thread class
defines several priority constants as: -
MIN_PRIORITY =1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Thread priorities can take value from 1-10.
To set the priority thread class provides setPriority ()
EXCEPTION HANDLING AND MULTITHREADING

Syntax: Thread.setPriority (priority value);

To see the priority value of a thread the method available is


getPriority().
Syntax: int Thread.getPriority ();

21) What is thread priority? How thread priority are set and
changed? Explain with example. (Summer 16) 8 marks
Thread Priority: Threads in java are sub programs of main
application program and share the same memory space. They are
known as light weight threads. A java program requires at least
one thread called as main thread. The main thread is actually the
main method module which is designed to create and start other
threads in java each thread is assigned a priority which affects the
order in which it is scheduled for running. Thread priority is used to
decide when to switch from one running thread to another.
Threads of same priority are given equal treatment by the java
scheduler. Thread priorities can take value from 1-10. Thread
class defines default priority constant values as
MIN_PRIORITY = 1
NORM_PRIORITY = 5 (Default Priority)
MAX_PRIORITY = 10

a) setPriority:
Syntax:public void setPriority(int number);
This method is used to assign new priority to the thread.

b) getPriority:
Syntax:public intgetPriority();
It obtain the priority of the thread and returns integer value.

Example:
class clicker implements Runnable
{
int click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p)
EXCEPTION HANDLING AND MULTITHREADING

{
t = new Thread(this);
t.setPriority(p);
}
public void run()
{
while (running)
{
click++;
}
}
public void stop()
{
running = false;
}
public void start()
{
t.start();
}
}
class HiLoPri
{
public static void main(String args[])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
EXCEPTION HANDLING AND MULTITHREADING

// Wait for child threads to terminate.


try
{
hi.t.join();
lo.t.join();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}

22) What is thread priority? Write default priority values and


methods to change them. (Summer 17) 4 marks
Thread Priority: In java each thread is assigned a priority which
affects the order in which it is scheduled for running. Thread
priority is used to decide when to switch from one running thread
to another. Threads of same priority are given equal treatment by
the java scheduler.
Default Priority Values:Thread priorities can take value from 1
to10.
Thread class defines default priority constant values as

MIN_PRIORITY = 1
NORM_PRIORITY = 5 (Default Priority)
MAX_PRIORITY = 10

a) setPriority:
Syntax:public void setPriority(int number);
This method is used to assign new priority to the thread.

b) getPriority:
Syntax:public intgetPriority();
It obtain the priority of the thread and returns integer value.
EXCEPTION HANDLING AND MULTITHREADING

23) What is synchronization? When do we use it? Explain


synchronization of two threads. (Winter 16) 4 marks
Synchronization:-
When two or more threads need access to a shared resource, they
need some way to ensure that the resource will be used by only
one thread at a time. The process by which this is achieved is
called synchronization.

Synchronization used when we want to –


a) prevent data corruption.
b) prevent thread interference.
c) Maintain consistency If multiple threads require an access to
an object
Program based on synchronization:
class Callme {
void call(String msg)
{
System.out.print("[" +msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
System.out.print("]");
}
}
class Caller implements Runnable
EXCEPTION HANDLING AND MULTITHREADING

{
String msg;
Callme target;
Thread t;
public Caller(Callmetarg,String s)
{
target=targ;
msg=s;
t=new Thread(this);
t.start();
}
public void run()
{
synchronized(target)
{
target.call(msg);
}
}
class Synch
{
public static void main(String args[])
{
Callme target=new Callme();
Caller ob1=new Caller(target,"Hello");
Caller ob2=new Caller(target,"Synchronized");
try
{
EXCEPTION HANDLING AND MULTITHREADING

ob1.t.join();
ob2.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
}
}

You might also like