Unit 5 Merged
Unit 5 Merged
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);
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
}
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().
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
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()
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 ()
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
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