Exception Handling and Multithreading
Exception Handling and Multithreading
AND MULTITHREADING
EXCEPTION HANDLING AND MULTITHREADING
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");
}}}
Eg.
class XYZ
{
XYZ();
{
// Constructer definition
}
void show() throws Exception
{
throw new Exception()
}
}
EXCEPTION HANDLING AND MULTITHREADING
}
}
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){}
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
}
catch (InterruptedExceptione){}
}
}
class Print
{
public static void main(String args[])
{
new EvenThread();
new OddThread();
}
}
{
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();
}
}
{
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();
}
}
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.");
}
}
Newborn State
Runnable State
Running State
Blocked State
Dead State
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
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
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
{
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 ");
}
}
}