0% found this document useful (0 votes)
33 views24 pages

Unit 5 Merged

Word press

Uploaded by

ShaikYusaf
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)
33 views24 pages

Unit 5 Merged

Word press

Uploaded by

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

Exception Handling

What is Error? Discuss different types of Errors in Java


It is Common to make mistake while developing as well as typing a program. A mistake might
lead to an error causing to program to produce the unexpected results.
An error may produce incorrect output or may terminate the execution of the program or even
may cause the system to crash. It is therefore important to detected and manage all the possible errors
conditions in the program, so that the program will not terminate or crash during of execution. Errors
may broadly classify into two types:
1. Compile-Time Errors. (Or) Syntactical Errors
2. Run-Time Errors.
1. Compile-Time Errors:
All Syntax errors will be detected by the Java Compiler and therefore these errors are known as
compile time errors. Whenever the compiler display an error it will not create “dot class file”. Therefor
it is necessary to correct the errors before we can successfully compile and run the program.
Most of the compile-time errors are due to typing mistakes. These errors are sometimes
very hard to find. To find these errors, we may need to check the code word by word. The most
common errors problems are:
1. Missing Semicolons Symbols (;).
2. Missing brackets in class and methods.
3. Misspelling identifiers and keywords.
4. Missing double quotes in strings.
5. Use of undeclared variables.
6. Use of “=” in the place of “ = = ” operator.
2. Run Time Error:
Sometimes a program may compile successfully creating dot class file, but may not run properly. Such
programs may produce wrong results due to wrong logic and may terminate due to errors. The most of
common Run-Time errors are:
1. Dividing an integer value by zero.
2. Accessing elements that are out of bound of an array.
3. Passing a parameter that is not a valid range or value of method.
4. Attempting to use a negative size of an array.
5. Converting invalid string into a number.
When these types of errors occurs, it generates an error message and stop the execution of a
program abnormally.
Program:

import java.lang.*; class RuntimeError


{

1
public static void main(String args[])
{
int a = 10;
int b = 5;
int c = 5;
int x = a/(b-c); // Diving by Zero.
System.out.println("X : = " + x);
int y = a/(b+c);
System.out.println("Y : = " + y);
}
}
When java run time tries to execute a division by zero, it generates an error condition which causes
the program to stop after displaying an appropriate message.

2
Threads in Java.
(Q) Defining what is Thread? Explain Single Tasking and Multi Tasking or Multi Threading
Threads?
Definition of Thread:
In java, “Thread” is a light weight process or execution of a group of statements. A Thread is similar
to a program that has a single flow of control.
(Or)
A thread is a sequence of execution with in and own flow of process.
Single-Thread:
A Thread is a similar to a program that has a single flow of control. It has beginning, a body, and
an end, and executed command sequentially. In fact, all main programs in our earlier examples can be
called Single-Threaded Programs. Every program will have at least one Thread as shown below:

**** Multi-Threading:
Java provides built-in support for multithreaded programming. A multi thread program contains two
or more parts that can run concurrently. Each part of such a program is called a thread, and each thread
defines a separate path of execution.

In the above figure main thread is main method program which is used to create multiple threads
namely A,B,C. Once the main thread execution begins, the thread A, B and C run concurrently and share
the resources jointly. Threads in java are subprogram of main application and share the same memory
space and hence they are called as “Light weight process”.
Advantages of Multi-Threads:
1. Multi-Threads is a powerful programming tool that makes Java distinctly different from its
fellow programming languages.
2. It enables programmers to do multiple things at one time.
3. They can divide a long program into threads and executed them in parallel.
4. Threads extensively used in Java-enabled browser called as “Hot Java”
1
Uses of Threads:
Threads are mainly used in Server-Side programs to serve the needs of multiple clients on a
network or internet. For this purpose, if we used threads in the server, they can do various jobs
(instructions) at a time, thus they can handle several clients.
Threads are also used to create games and animations. In many games, generally we have to
perform more than one task simultaneously.

Deamon Threads:
A Deamon thread that executes continuously. Deamon threads are service providers for other
threads. Generally it is a background service thread which runs as a low priority thread and performs
background operations like garbage collection, releasing memory of unused objects and removing
unwanted entries from the cache. Most of the JVM threads are daemon threads.
To make a thread ‘t’ as a daemon thread use setDaemon() as follows.
t.setDaemon(true);

Explain how many ways to create a threads in Java?


Creating Threads:
Creating a thread in Java is simple. Threads are created with the help of run() in java. The run()
method is the heart and soul of an thread. A typical run() would appear as follow:
public void run()
{
--- - - - -(Statements for implementing Threads)
----------
----------
}
The run() method must be invoked(called) by an object of the concerned thread. This can be
done by creating the thread and initiating it with the help of another thread method called start(). A new
thread can be created in to two ways:
I. By extending Thread Class. (or) Creating a Thread Class
II. By Implementing Runnable Interface. (or) By Converting a Class to a Thread.
I. By Extending a Thread Class: Define a class that extends thread class and override its run()
method with the code required by the thread.
II. By Implementing Runnable Interface: Define a class that implements “Runnable” interface. The
Runnable interface has only one method run() which is to be defined in the method with the code to
be executed by Thread

2
Creating a New Thread by Extending a Thread Class:
The first method of creating a thread is simply by extending the thread class. The thread class is
defined in the java.lang package. This gives access to all the thread methods directly. It includes the
following steps:
(a). Declare the class as extending the Thread class.
(b). Implement the run()
(c). Create a thread object and call the start() to initiate the thread execution.
(a). Declaring the Class: The Thread class can be extended as follows:
class MyThread extends Thread
{
..........
..........
..........
}

(b). Implementing the run() Method: The run() method has been inherited by the class MyThread. We
have to override this method in order to implement the code to be executed by our Thread. The
basic implementation of run() is
public void run()
{
Thread Code
}

(C) Starting New Thread:


To invoke run() first we must create the object of the concerned thread and call the start
method of the thread class.
MyThread threadA = new MyThread();
threadA.start(); // Invokes run() method.
The first line creates a new object of the class MyThread. Now thread is in new borned state.
The second line calls the start() method creating the thread to move into the Runnable state. Then,
the Java runtime will schedule the thread to run by invoking its run() method. Now, the thread is said to be
in the running state.
Write a Java program to illustrate Creating Threads by using Thread Class in Java?
import java.lang.*;
class A extends Thread
{
public void run()
{
for(int i=1; i<=5; i++)
{
System.out.println("\t From Thread A : i = " +i);
3
}
System.out.println("Exit From Thread A
");
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<=5; j++)
{
System.out.println("\t From Thread B : j = " +j);
}
System.out.println("Exit From Thread B ");
}
}
class C extends Thread
{
public void run()
{
for(int k=1; k<=5; k++)
{
System.out.println("\t From Thread C : k = " +k);
}
System.out.println("Exit From Thread C ");
}
}
class ThreadTest
{
public static void main(String args[])
{
new A().start(); // Start the Running of Thread.
new B().start();
new C().start();
}
}
Save: ThreadTest.java
Compile: javac ThreadTest.java
Run: java ThreadTest

(II). By Converting a Class to a Thread. (or) By Implementing Runnable Interface:


Define a class that implements ‘Runnable’ interface. The Runnable interface has only one method
run(), that is to be defined in the method with the code to be executed by the Thread.

Step 1: Declare the class as implementing the Runnable Interface.


Step 2: Implement the run() method.
4
Step 3:Create a thread by default object that is instantiated from this runnable class as the target of
thread.
Step 4: call the threads start() method to run the thread for execution.
Declaring the Class as Runnable Interface: The Runnable interface can extend as follows:
class MyThread implements Runnable
{
---------
}
Write a Java program to illustrate for implementing Runnable Interface in Java?
import java.lang.*;
class Runnably implements Runnable // Step 1
{
public void run() // Step 2
{
try
{
while(true)
{
Thread.sleep(10);
System.out.println("Runnable Thread in Java.");
}
}
catch(InterruptedException ex)
{
e.prinStackTrace();
}
}
}
class RunnableTest
{
public static void main(String args[])
{
Runnably ry = new Runnably();
Thread t = new Thread(ry); // Step 3.
t.start(); // Step 4.
}
}
Save: RunnableTest.java
Compile: javac RunnableTest.java
Run: java RunnableTest

5
Stopping a Thread: Whenever we want to stop a thread from running further, we may do this by calling
its stop() method, like:
MyThread.stop();
This statement causes the thread to move to the dead state. A thread will also move to the dead
state automatically when it reaches the end of its method. The stop() method may be used when the
premature death of a thread is desired.
Blocking a Thread: A Thread can also be temporarily suspended or blocked from entering into
the runnable and subsequently running state by using either of the following thread methods:
sleep() // Blocked for a specified time.
suspend() // Blocked Unit further orders.
wait() // Blocked Unit Certain Condition occurs.
These methods cause the thread to go into the blocked (or not runnable) state. The thread will
return to the runnable state when the specified time is elapsed in the case of sleep(), the resume() method
is invoked in the case of suspend(), and the notify() method is called in the case of wait().

(Q) Explain how to terminating a Thread?


A Thread will terminated automatically when it comes out of run() method. To terminate the
Thread on our own logic
Write a Java program to illustrate how to terminate thread by pressing enter key?
import java.io.*;
class MyThread extends Thread
{
boolean stop = false;
public void run()
{
for(int i = 1; i<=10000; i++)
{
System.out.println(i);
if(stop)
return; //Come out of run()
}
}
}
class TerminateThread
{
public static void main(String args[]) throws IOException
{
MyThread obj = new MyThread();
Thread t = new Thread(obj);
t.start();
6
System.in.read(); // stop the thread when Enter key pressed
obj.stop=true;
}
}
Save: TerminateThread.java
Compile: Javac TerminateThread.java
Run: java RunableThread
Output: 1 2 3 4 5 6 7 8 9 10 11 12 <Enter>

(Q) Explain about Single Tasking using a Thread?


A Thread can be executing one task at a time. Suppose there are 3 tasks to be executed. We can
create a thread and pass the 3 tasks one by one to the thread. For this purpose, we can write all these
tasks separately in separately in separate methods: task1(), task2(), task3(). These methods should be
called from run() method, one by one. Remember, a thread executes only the code inside the run()
method. It can never execute other methods unless they are called from run().
Write a Java program to illustrate Single Tasking using a Thread?
import java.io.*;
class MyThread implements Runnable
{
public void run()
{
task1();
task2();
task3();
}
void task1()
{
System.out.println("This is Task 1");
}
void task2()
{
System.out.println("This is Task 2");
}
void task3()
{
System.out.println("This is Task 3");
}
}
class SingleTask
{
public static void main(String args[])
{
7
MyThread obj = new MyThread();
Thread t2 = new Thread(obj);
t2.start();
}
}
Save: SingleTask.java
Compile: javac SingleTask.java
Run: java SingleTask
Output: This is Task 1
This is Task 2
This is Task 3

(Q) Explain about Multi tasking using threads in Java?


In multi tasking, several tasks are executed at a time. For this purpose, we need more than one
thread. For example, to perform 2 tasks, we can take 2 threads and attach them to the 2 tasks. Then those
tasks are simultaneously executed by the two threads. Using of more than one thread is called multi
threading.
Write a Java program to create two threads working simultaneously two tasks at a time?

public class MyThread extends Thread


{
String task; // Declare a String variable to represent task.
MyThread(String task)
{
this.task = task;
}
public void run()
{
for(int i = 1; i <= 5; i++)
{
System.out.println(task+ " : " +i);
try
{
Thread.sleep(1000); // Pause the thread execution for 1000 milliseconds.
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
8
class Theatre
{
public static void main(String[] args)
{
MyThread th1 = new MyThread("Cut the Ticket: ");
MyThread th2 = new MyThread("Show your seat number: ");
Thread t1 = new Thread(th1);
Thread t2 = new Thread(th2);
t1.start();
t2.start();
}
}
Save: MyThread.java
Compile: Javac MultiTaskThread.java
Run: java MultiTaskThread
Output: Cut the Ticket: 1
Show your seat number: 1
Cut the Ticket: 2
Show your seat number: 2
Cut the Ticket: 3
Show your seat number: 3
Cut the Ticket: 4
Show your seat number: 4
Cut the Ticket: 5
Show your seat number: 5

(Q) Explain about Multiple Threads acting a single object?


When two people performs the same ask then they need same object (run()) to be executed each time.
For example take the case of railway reservation, every day several people want reservation of a berth for
them. The procedure to reserve the berth is same for all the people. So we need same object with same
run() method to be executed repeatedly for all the peoples (threads).
Think that only one berth is available in a train, and two passengers (threads) are asking for that
berth. In reservation counter no:1, the clerk has sent a request to the server to allot that berth to his
passenger, in counter no:2, the second clerk has also sent a request to the server to allot that berth to his
passenger. Let us see now whom those berth is allotted.
Write a Java program showing two threads acting upon a single object?
class Reserve implements Runnable
{
int available = 5;
9
int wanted;
Reserve(int i)
{
wanted = i;
}
public void run()
{
System.out.println("Available Berths = " +available);
if( available >= wanted)
{
String name = Thread.currentThread().getName();
System.out.println(wanted+ " Berth Reserved for " +name);
try
{
Thread.sleep(1500);/*Wait for printing the ticket*/
available=available-wanted;
}
catch(InterruptedException ie) {}
}
else
System.out.println("Sorry, No berths");
}
}
class BerthsAvailable
{
public static void main(String args[])
{
Reserve obj = new Reserve(1);
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
t1.setName("First Person");
t2.setName("Second Person");
t1.start();
t2.start();
}
}
Save: BerthsAvailable.java
Compile: Javac BerthsAvailable.java
Run: java BerthsAvailable

Output 1: Available Berths = 5


Available Berths = 5
1 Berth Reserved for First Person
10
1 Berth Reserved for Second Person
(Q) Explain various thread class methods to perform thread tasks and control thread
behaviours?
Java Thread class: Java provides Thread class to achieve thread programming. Thread c l a s s
provides constructors and methods to create and perform operations on a thread. Thread c l a s s
extends Object class and implements Runnable interface.
The Thread calls in the “java.lang” package allow creating and managing thread. Each thread is a
separate instance of its class. Some Constructor for Thread is as follow:
Thread ();
Thread (Runnable r)
Thread (Runnable r, String S)
Thread (String S)
Here ‘r’ is a reference to an object that implements Runnable interface and “S” is a string used to identify
the Thread
The following table shows some ‘static’ methods provided by this class

Method Description
Thread.currentThread() Returns a reference to the Current Thread.
void sleep(long msec) throws Interrupted Exception Causes the Current Thread to wait for milliseconds.
Thread.yield() Causes the Current Thread to yield control of
the processor.

11
12
IMP ********** (Q). Explain the Life-Cycle / State Transitions of a Thread with examples?
During the life-time of a thread, the thread goes in and out of several states. These states are
used to control the flow of execution of several parallel threads. The threads scheduler of Java Virtual
Machine (JVM) moves the threads from one state to another state when we call different methods. Each
thread in its entire life of execution may be in one of the following states.
1. New Born / New State.
2. Runnable Sate
3. Running State
4. Sleeping / Waiting / Blocked State
5. Dead State.
A thread is always in one of these 5 stages. It can move from one stage to another

Fig:Life-Cycle / State Transitions of a Thread.

New Born Runnable Running Blocked Dead

1. New Born: When we created a thread object the thread is born and is said to be in new born state.
At this state, we do only one of the following things with it:
1. Schedule it for running using start() method.
2. Kill it using stop() method.
13
If scheduled, it moves to the Runnable state. If we attempt to use any other methods at this stage, an
exception will be thrown.

New Born

start() stop()

Runnable State Dead State

2. Runnable State:
The runnable state means that the thread is ready for execution and is waiting for the availability of
the processor. The thread has joined the queue of threads that are waiting for execution. If all threads have
equal priority, then they are given time slots for execution in round robin fashion i.e first-come first server
manner. The thread that give up control joins the queue at the end and again waits for its turn. This process
of assigning time to threads is known as time slicing.
If we want a thread to give up control to another of equal priority before its turn comes, we use the
yield() .
3. Running Sate: Running State means the processor has given its time to the thread for its execution.
The thread may come to this stage more than once in its life time. A thread enters this stage whenever its
run() method is called. A running thread may goes into any of the following situation.

yield ()

Running thread Runnable Threads

1. It has been suspended using suspend(). A suspended thread can be revived(come back) by using the
resume (). This useful when we want to suspend a thread for sometime due to certain reasons, but
do not want to kill it.
suspend

resume

Running Runnable Suspended.


2. We can put a thread to sleep for a specified time period using sleep(time) where time is in
milliseconds. The tread re- enters the Runnable state as soon as this time period is elapsed.

14
sleep (t)

after(t)
Running Runnable Suspended.
3. It has been told to wait until some event occurs. This done using the wait () method. The thread can
be scheduled to run again using the notify() method.
wait

notify
Running Runnable Waiting.

4. Blocked State:
A thread is said to be blocked when it is prevented from entering into the runnable state. This
happens when the thread is suspended, sleeping or waiting in order to satisfy certain requirement.
A block thread is considered “not runnable” but not dead and can run again.
5. Dead State:
A running thread ends its life when its completed executing its run() method. It is natural death.
A thread can be killed as soon as it is born or while it is running or even when it is in “not runnable”
condition.

15

You might also like