Java_17_Multithreading
Java_17_Multithreading
Multithreaded Programming
12.1 INTRODUCTION
Those who are familiar with the modern operating systems such as Windows 95 and Windows XP may
recognize that they can execute several programs simultaneously. This ability is known as multitasking. In
system's terminology, it is called multithreading.
Multithreading is a conceptual programming paradigm where a program(process) is divided into two
or more subprograms (processes), which can be implemented at the same time in parallel. For example,
one subprogram can display an animation on the screen while another may build the next animation to be
displayed. This is something similar to dividing a task into subtasks and assigning them to different people
for execution independently and simultaneously.
In most of our computers, we have
class ABC
only a single processor and therefore, in
Beginning reality, the processor is doing only one
thing at a time. However, the processor
switches between the processes so fast that
it appears to human beings that all of them
are being done simultaneously.
Single-threaded Java programs that we have seen and
body of execution
discussed so far contain only a single
sequential flow of control. This is what
happens when we execute a normal
program. The program begins, runs through
End a sequence of executions, and finally
ends. At any given point of time, there
is only one statement under
execution.
Fig. 12.1 Single-threaded program A
thread issimilar to a program thathas
a single flow of control. It has a
abody, and an end, and executes commands sequentially. In fact, all main programs in our earlier beginning,
examples
can be called single-threaded programs. Every program will have at least one thread as shown in Fig, 12L.
Multithreaded Programming 199
12,2
CREATING THREADS
Creating threads in Java is simple. Threads are
called run( ). The run() method is the heart andimplemented
soul of
in the form of objects that contain a
method
and is the only method in which the any thread. It makes up the entire body of athread
as follows: thread's behaviour can be implemented. A typical run( )
would appear
public void run( )
{
When we start the new thread, Java calls the thread's run() method, so it is the run( ) where all
the
action takes place.
class ThreadTest
From Thread 1
Fiom Thread 2
From Thread
From Thread 2
From Thread C k 1
From Thread
From Thread 3
From Thread A 4
From Thread 3
From Thread B 4
From Thread 3
From Thread 4
From Thread 5
Exit from
From Thread B 5
Exit from B
From Thread k = L
Exit from C
Second run
From Thread A
From Thread 2
From Thread
From Thread 2
From Thread 3
From Thread 4
From Thread
From Thread 2
From Thread C 3
From Thread C
From Thread 5
Exit from A
From Thread B 4
From Thread B 5
From Thread =
5
Exit from C
From Thread 5
Exit from B
Similarly, it starts C thread. By the time the main thread has reached the end of
are a total of four separate threads running in parallel. its main method. there
We have simply initiated three new threads and
started them. We did not hold on to them any further.
Thev are running concurrently on their own. Note
that the output from the
threads are not specially
sequential. They do not follow any speciic order. They are running
executes whenever it has a chance. Remember, once the independently of one another and each
the order in which they may execute threads are started, we cannot decide with certainty
statements, Note that a second run has a different output
sequence.
Primer
Programming witlh Java: A
204
A THREAD
12.4
STOPPING AND BLOCKING
Blocking a Thread
blocked from entering into the runnable and subsequently
Athread can also be temporarily suspended or methods:
running state by using either of the following thread
sleep( ) 1/ blocked for a specified time
suspend ( ) // blocked until further orders
wait ( ) // blocked until certain condition occurs
state. The thread will return
These methods cause the thread to go into the blocked (or not-runnable)
the resume( ) method is
10 the runnable state when the specified time is elapsed in the case of sleep( ),
invoked in the case of suspend(), and the notify() method is called in the case of wait( ).
Runnable Threads
Running
Thread
resume
2. It has been made to slecp. We can put athrcad to sleep for a specified time period using the
sleep(tinme) wherc time is in milliseconds. This means that the thread is out of 1the
queue meththisod
during
time period. The thread re-enters the runnable state as s0onas this time period is elapsed
slecp(t)
after(t)
notify
Running Runnable
Waiting
Fig. 12.8 Relinquishing control using wait() method
Blocked State
A thread is said to be blocked when it is prevented from entering into
the runnable state and subsequently
the running state. This happens when the thread 1S Suspended, sleeping, or waiting in order to
requirements. A blocked thread is considered "not runnable" but not dead and therefore fullysatisfy certain
gualified to
run again.
Dead State
Every thread has a life cycle. A running thread ends its life when it has completed executing its run( )
method. It is a natural death. However, we can kill it by sending the stop message to it at any state thus
causing apremature death to it. A thread can be killed as soon it 1s born, or while it is runnine or even
when it is in "not runnable'" (blocked) condition.
if (i==1) yield( ):
System. out.println ("\tFrom Thread A : i= " +i);
$ystem . out.println("exit from A " ):
if (j=3) stop( );
System.out.println("Exit from B ");
sleep (1000) ;
catch (Exception e)
// Killed thread
Multithreuded Programming 209
catch (InterruptedException e)
catch (Exception e)
77 Any other
The intNumber is an integer value to which the thread's priority is set. The Thread class defines several
priority constants:
MIN PRIORITY =
NORM PRIORITY =
5
MAX PRIORITY 10
default
The intNumber may assume one of these constants or any value between 1and 10. Note that the
setting is NORM PRIORITY.
Most user-level processes should use NORM _PRIORITY, plus or minus 1. Back-ground tasks Such
as network I/O and screen repainting should use avalue very near to the lower limit. We should be
very cautious when trying to use very high priority values. This may defeat the very purpose of using
multithreads.
By assigning priorities to threads, we can ensure that they are given the attention (or lack of i) they
deserve. For example, we may need to answer an input as quickly as possible. Whenever multiple threads
are ready for execution, the Java system chooses the highest priority thread and executes it. For a thread of
lower priority to gain control, one of the following things should hapDen:
end of run( ).
I. Itstops running at the
2. Itis made to sleep using sleep().
3. It is told to wait using wait( ).
210 Programming with Java: A Primer
However. if another thread of a higher priority comes along, the currently running thread will be
preempted by the incoming threadthus forcing the current thread to move to :he runnable state. Remember
that the highest priority thread always preempts any lower priority thrcads.
Program 12.3 and its output illustrate the effect of assigning higher priority to a thread. Note that
although the thread A started first, the higher priority thread B has preempted it and started printing the
output first. Immediately, the thread C that has been assigned the highest priority takes control over the
other two threads. The thread A is the last to complete.
class ThreadPriority
threadC started
From Thread C : k = 1
From Thread C : k =
2
From Thread C : k = 3
From Thread C: k = 4
Exit from C
End of main thread
From Thread B: j =
From Thread B: i = 4
Exit from B
threadA started
From Thread A :i =1
From Thread A :i = 2
From Thread A : i = 3
From Thread A : i = 4
Exit from A
SYNCHRONIZATION
12.9
So far swe have seen threads that use their own data and methods provided inside their run( ) methods.
What happens when they try to use data and methods outside themselves? On such occasions, they may
compete for the same resources and may lead to serious problems. For example, one thread may try to read
a record from a file while another is still writing tothe same file. Depending on the situation, we nay get
strange results. Java enables us to overcome this problem using a technique known as synchronization.
In case of Java, the keyword synchronised helps to solve such problems by keeping awatch on such
locations, For example, the method that will read information from a file and the method that will undate
the same file may be declared as synchronized. Example:
212 Programming with Java: A Primer
When we declare a method synchronized, Java creates a "monitor and hands it over to the thread
that calls the method first time. As long as the thread holds the monito, no other thread can enter the
synchronized section of code. A monitor is like a key and the thread that holds the key can only open the
lock.
It isalso possible tomark a block of code as synchronized as shown below:
synchronized ( lock-object )
Whenever a thread has completed its work of using synchronized method (or block of code), it will hand
over the monitor to the next thread that is ready to use the same resource.
An interesting situation may occur when twO or more threads are waiting to gain control of a resource.
Due to some reasons, the condition on which the waiting threads rely on to gain control does not happen.
This results in what is known as deadlock. For example, assume that the thread A must access Methodl
before it can release Method2, but the thread B cannot release Methodl until it gets hold of Method2.
Because these are mutually exclusive conditions, a deadlock occurs.The code below ilustrates this:
Thread A
synchronized methoa2
synchronized method1( )
Thread B
synchronized method1( )
synchronized method2 ( )
class RunnableTest
Thieaik : l0
End of Thread
notifyall(): Resumes all the threads that are in sleep mode. The execution of these threads happens as
per priority. The object class declaration of notifyall() method is shown below:
final void notifyall ()
wait(): Sends the calling thread into the sleep mode. This thread can now be activated only by
notify() or notifyall() methods. One can also specify the time for which the thread has to wait.
The desired waiting time period is specified as an argument to the wait() method. The object class
declaration of wait() method is shown below:
final void wait ()
Allthe above methods are declared in the root class, i.e., Object. Since, the methods are declared as final
they cannot be overridden. All the three methods throw InterruptedException.
Thread Th;
boolean suspend flag, stop flag;
Multithreaded Programming 215
Th.start0;
int j=l;
while (++j<20)
í synchronized (this) {
while (suspend flag)
( wait();}
ii (stop flag)
break; }
try{ stop("SRS");
new sus res
Sus res stop S RS T =
T is created and started "):
Systen. out.println ("Thread s RS
Thread.sleep (2000) ;
SRS T.my suspend() ;
ST is suspended ") ;
System. out.println ("Thread SR
Thread.sleep (2000);
12.12 SUMMARY
Athread is a single line of execution within a program. Multiple threads can run concurrently in a single
program. Athread is created either by subclassing the Thread class or implementing the Runnable
interface. We have dscussed both the approaches in detail in this chapter. We have also learned the
following in this chapter:
How to synchronize threads,
How to set priorities for threads, and
" How to control the execution of threads
Carefulapplication of multithreading willconsiderably improve the execution speed of Java programs.
P KEY TERMS
Thread, Multithread, Multitask, Concurrency, Lightwcight Processes, Time-slicing, Priority, Synchronization,
Deadlock.
REVIEW QUESTIONS
12.1 What is a thread?
12.2 What is the difference between multiprocessing and multithreading? what is to be done to implement these in a
program?
12.3 What Java interface must be implemented by all threads?
12.4 How do we start a thread?
12.5 What are the two methods by which we may stop threads?
12.6 What is the difference between suspending and stopping a thread?