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

Java_17_Multithreading

Uploaded by

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

Java_17_Multithreading

Uploaded by

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

12

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

Aunique property of Java is its Main Thread


support for multithreading. That is
Java enables us to use multiple flows
of control in developing programs.
Each flow of control may be thought Main method
module
of as a separate tiny program (or
module) known as a thread that runs in
parallel to others shown
Fig. 12.2. A program that contains
multiple flows of control is known as
multithreaded program. Figure 12.2 start, start start
illustrates a Java program with four
threads, one main and three others.
The main thread is actually the main
method module, which is designed to
create and start the other three threads.
namely A, B and C. switching switching
Once initiated by the main thread,
the threads A, B, and Crun concurrently
and share the resources jointly. It is
like people living in joint families and ThreadA Thread B Thread C
sharing certain resources among all
of them. The ability of a language to Fig. 12.2 A Multithreaded program
support multithreads is referred to as
concurrency. Since threads in Java
are subprograms of amain application program and share the same memory space, they are known as
lightweight threads or lightweight processes.
It is important to remember that threads running in parallel' does not really mean that they actually run
at the same time. Since all the threads are running on a single processor, the flow of execution is
shared
between the threads. The Java interpreter handles the switching of control between the threads in such a
way that it appears they are running concurrently.
Multithreading is a powerful programming tool that makes Java distinctly different from its fellow
programming languages. Multithreading is useful in a number of ways. It enables programmers to do
multiple things at one time. They can divide a long program (containing operations that are conceptually
concurrent) into threads and execute them in parallel. For example, we can send tasks such as printing
into the background and continue to perform some other task in the foreground. This approach
would
considerably improve the speed of our programs.
Threads are extensively used in Java-enabled browsers such as HotJava. These browsers can
download a fle to the local computer, display a Web page in the window, output another Web page to a
printer and so on.
Any application we are working on that requires two or more things to be done at the same time is
probably a best one for use of threads.
200
Programming with Java: APrimer

Table 12,1 Difercnce betuvcen multithreading and multitasking


Multithreading Multitasking
It is a programming concept in which a program or a It is an opcrating system concept in which multinle
process is divided into two or morc subprograms or tasks are performed simultaneously.
threads that are executed at the samec time in parallcl.
lt supports execution of multiple parts of a single
program simultaneously.
It supports execution of multiple
prograrms
simultaneously.
The processor has to switch betwcen different parts The processor has to switch between different
or threads of a
program. programs or processes.
It is highly efficient. It is less efficient in comparison to multithreading.
A thread is the smallest unit in
multithreading. A program or process is the smallest unit in a
multitasking environment.
It helps in developing eficient
It is
programs. It helps in developing efficient operating systems.
cost-effective in case of context switching. It is expensive in case of context switching.

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( )
{

(statements for implementing thread)

The run() method should be invoked by an


creating the thread and initiating it with the help ofobject of the concerned thread. This can be
another thread method called start ). achieved by
A new thread can be created in two
1. By creating a thread
ways.
class:. Define a class that extends Thread
method with the code required by the thread. class and override its run )
2. By converting a class to a
thread:
Runnable interface has only one method,Define
a class that implements
run( ), that 1s to be defined in theRunnable intertace. The
beexecuted by the thread. method with the code to
The approach to be used depends on
another class, then we have no choice butwhat the class we are creating
to implement the Runnable requires. If it requires to extend
have two superclasses. interface, since Java classes cannot

12.3 EXTENDING THE THREAD CLASS


We can make our class runnable as thread by
extending theclass
all the thread methods directly. It includes the following steps: java.lang.Thread. This gives s accéss to
Multithreaded P'roqramming 201

Declare the class as Cxtending the Thread class.


lmplment the run( )methed that is responsible for cxecuting the scquence of code that the
thread
iCrate a thrcad objcct and call the start() ncthodto initiate the
thrcad cxecution.
Declaring the Class
The Thread class can be extended as follows:
ciass MyThread extends Thread

Now we have a new type of thread MyThread.

Implementing the run() Method


The run(0 method has been inherited by the class MyThread. We have tooverride this
method in order to
implement the code to be executed by our thread. The basic implementation of run() will look like this:
public void run ()

// Thread code here

When we start the new thread, Java calls the thread's run() method, so it is the run( ) where all
the
action takes place.

Starting New Thread


To actually create and run an instance of our thread class, we must write the following:
MyThread aThread = new MyThread( );
aThread. start(); 1/ invokes run() nmethod
The first line instantiates a new object of class MyThread. Note that this statement just
creates the
object. The thread that will run this object is not yet running. The thread is in a newborn state.
The second line calls the start( ) method causing 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 thrcad is said to be in
the running state.

An Example of Using the Thread Class


Program 12.1 illustrates the use of Thread class for creating and running threads in an application, The
Program creates three threads A, B, and Cfor undertaking three different tasks. The main method in the
IhreadTest class also constitutes another thread which we may call the "main thread".
Ihe main thread dies at the end of its main method. However, before it dies, it creales and starts all the
three threads A. B. and C. Note the statements like
I'rogromminywith Jova: APrimer
202

new A .start ():


in the main thread. This is jIst a comypact way of starting a thrcad. This is equivalent to:
AthreadA hew A );
t hieaaA.stat();
Immediatels after the thrcad Ais started, there will be two threads running in the prograrn: the mae
thrcad and the thread A. The start( ) method returns back to thc main thrcad immediately aftcr
run() mcthod. thus allowing the main thrcad to start the thrcad B. invoking the
Program 12,1 Creating threads usingthe thread class
Ciass Aextends Thread

public void run( )

for (int i=l; i<=5; it+)


System. out.println ("\t From ThreadA : i = + i);

System. out. println ("Exit from A ");

ciass B extends Thread

public void run( )

for (int j=1; j<=5; j+t)

System. out .println("\tFrom Thread B:j = + j);

System. out. println("Exit from B "):

class Cextends Thread


public void run (

for (int k=l; k<=5; kt+)

System. out.println ("\tFrom Thread C: k = " + k);


System. out. println ("Exit from C ");

class ThreadTest

public stat.ic void na in(String args [ 1)


new A ().start()i
new B
().start ( ):
new C().start();
Multithreaded Programming 203

Output of Program 12.1 would be:

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

Stopping a Thread method. like:


thrcad from running further, we may do so by call1ng its stop()
Whenevcrwe want to stop a
aThread. stop();
also mOve to the dead stete
causes the thrcad to move to the dead state. A thread will
This statement may be used when the prematir
automatically when it reaches the end of its method. The stop( ) method
death ofathread is desired.

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( ).

12.5 LIFE CYCLE OF A THREAD


During the life time of a thread, there
are many states it can enter. They New Thread Newborn
include:
1. Newborn state start stop
2. Runnable state
3. Running state
4. Blocked state Active
Running (Runnable) stop Killed
5. Dead state Thread Dead Thread
yicld
Athread is always in oneof these
five slates. It can move from one
state to another via a variety of ways suspend resume
as shown in Fig. I2.3. sleep notify stop
Wait
Newborn State
When we create athread objcct, the Idle Thrcad
Blocked
thread is born and is said to be in (Not Runnable)
newhor state. The thread is not yet
scheduled for running. At this slate, Fig. 12.3 State transition diagram of athread
we can do only one of the following
things with it:
Schedule it for running using start() method.
Kill it using stop()method.
Multithreuded Programming 205

If scheduled, it moves to the runnable state


any other method
(Fig. 12.4). If we attempt to use thrown. Newborn
be
atthis stage, an exceptionwill
Runnable State
start stop
The runnable state means that the thread is ready
forexecution and is waiting for the availability of
the
the processor. That is, the thread has joined
aueue of threads that are waiting for execution. If
all threads have equal priority, then they are given Runnable Dead
time slots for execution in round robin fashion. state
state
ie.. first-come, first-serve manner. The thread that
relinquishes control joins the queue at the end and
again waits for its turn. This process of assigning thread
as time-slicing. Fig. 12.4 Scheduling a newborn
time to threads is known
However, if we want a thread to relingquish
do so by using the yield() method
control to another thread to equal priority before its turn comes, we can
(Fig. 12.5).
yield

Runnable Threads
Running
Thread

Fig. 12.5 Relinquishing control using yield() method

Running State runs until


means that the processor has given its time to the thread for its execution. The thread
Running
relinguishes control on its own or it is preempted by a higher priority thread. A running thread may
it situations.
relinquish its control in one of the following using the
A suspended thread can be revived by
1. It has been suspended using suspend( ) method. we want to suspend a thrcad for some time due to
resume)method. This approach IS useful when
wantto kill it.
certain reason, but do not
suspend

resume

Running Runnable Suspended

Fig. 12.6 Relinquishing control using suspend() method


206 P'royramming with Java: APrimer

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)

Running Runnable Suspended

Fig. 12.7 Relinquishing control using sleep() method


3. Ii has been toldto wait until some event occurs. This is done using the wait( )method. The thread
can be scheduled to run again using the notify() method.
wait

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.

12.6 USING THREAD METHODS


We have discussed how Thread class methods can be used to control the behaviour of a thread. We have
used the methods start() and run( ) in Program l2.1. There are also methods that can move athread from
one state toanother. Program 12.2 illustrates the use of yield( ), sleep( ) and stop() methods. Compare the
outputs of Programs 12.1 and 12.2.
Program 12.2 Use of yield(),stop), and sleep() methods
Class A extends Thread

public void run( )


for (int i 1; i<=5; i++)

if (i==1) yield( ):
System. out.println ("\tFrom Thread A : i= " +i);
$ystem . out.println("exit from A " ):

class B extends Thread

public void run( )


for (int i=l; i<=5; j++)

System. out.println ("\tFrom Thread B:j =

if (j=3) stop( );
System.out.println("Exit from B ");

class Cextends Thread


public void run( )
for (int k=l: k<=5; k++)

System. out. println("\tFrom Thread C : k = " +k):


if (k==l)
try

sleep (1000) ;
catch (Exception e)

System . out. println( "Exit from C "):

class ThreadMe thods


Dublic static void main(String args[ ])
A threadA new A();
B threadB =
new B( );
C threadC new C( );
System. out.println ("Start thread A");
threadA.start( ):
System.out.println("Start thread B") ;
thread3.start( );
208 Programming withJava: A Primer

System.out .println ("Start thread C");


threadC,staIt( );
System, out .println ("End of main thread") ;

Here is the output of Progran 12.2:


Start thread A
Start thread B
Start thread C
From Thread B: j = 1
From Thread B: i = 2
From Thread A : i = 1
From Thread A : i = 2
End of main thread
From Thread C: k = 1
From Thread B : j = 3
From Thread A : i = 3
From Thread A : i = 4
From Thread A: i = 5
Exit from A
From Thread C: k = 2
From Thread C : k = 3
From Thread C: k = 4
From Thread C : k = 5
Exit from C

Program 12.2 uses the yield()method in thread Aat the


started first, has relinquished its control to the thread B. Theiterationi=1. Therefore, the thread A, although
implementing the for loop only three times. Note that it has notstop( ) method in thread B has killed it after
reached end of run( ) method. The thread C
started sleeping after executing the for loop only once.
When it woke up (after 1000
and therefore was running alone. The milliseconds),
two threads have already completed their runs the other
earlier than the other three threads. main thread died much

12.7 THREAD EXCEPTIONS


Note that the call to sleep() method is
enclosed in a try block and followed by a catch block. This is
necessary because the sleep() method throWs an exception, which should be caught. If we fail to catch the
exception, program will not compile.
Java run system will throw
athread cannot handle in the IllegalThreadStateException whenever we
given state. For example, asleeping thread attempt invoke a method that
to
method because asleeping thread cannot receive any cannot deal with the resume )
instructions.
method when it is used on a blocked (Not Runnable) thread. The same is true with the suspend( )
Whenever we calla thread method that is likely to throw an
exception handler to catch it. The catch statement may take one exception, we have to supply an appropriate
of the following forms:
catch (ThreadDeath e)

// Killed thread
Multithreuded Programming 209

catch (InterruptedException e)

// Cannot handle it in the current state

catch (Illegal Argument Exception e)

7/ Illegal method argument

catch (Exception e)

77 Any other

Exception handling is discussed in detail in Chapter 13.

12.8 THREAD PRIORITY


In Java, each thread is assigned a priority, which affects the order in which it is scheduled for running. The
threads that we have discussed so far are of the same priority. The threads of the same priority are given
equal treatment by the Java scheduler and, therefore, they share the processor on a first-come, first-serve
basis.
Java permits us to set the priority of a thread usingthe setPriority( )method as follows:
ThreadName. setPriority (intNumber) ;

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.

Program 12.3 Use of priority in threads


class A extends Thread
{
public void run( )

System. out. println("threadA started") :


for (int i=l; I<=4; i++)

System. out. println ("\tFrom Thread A : i = +i);


System. out. println(Exit from A ");

class B extends Thread


public void run( )
{
System. out.println ("threadB started");
for (int j=1; j<=4; j++)

System. out. println ("\tFrom Thread B: i = "


System. out.. println ("Exit from B ");

class C extends Thread

public void run( )


System.out.println(threadC started");
for (int k=1; k<=4; kt+)

System. out. println (\tFrom Thread C :k = " + k);

System. out.printin ("Exit from C "):

class ThreadPriority

public static void main (String args[ JD


A threadA new A();
B threadB = new B();
C threadC = new C ) ;

threadC. setPriority (Thread.MAX PRIORITY);


Multithreanded Programming 211

threadB, setPririty(threadA . qet Priority( )+1)


threadA.setPrioirty(Thread. MIN PRIORITY):
System. out.print ln("Start thread N"):
threadA. start();

System. out.println ("Start thread B"):


threadB. start( );
System. out.println("Start thread C"):
threadC.start);

System.out.println ("End of main thread") ;

Output of Program 12.3:


Start thread A
Start thread B
Start thread C
threadB started
From Thread B :j = 1
From Thread B =

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

synchronized void update( )

// code here is synchronized

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 )

// code here is synchronized

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 ( )

12.10 IMPLEMENTING THE RUNNABLE' INTERFACE


We stated earlier that we can create threads in two ways: one by using the extended Thread class an
another by implementing the Runnable interface. We have already discussed in detail how the Thread
Multithreaded Programming 213
for ereating and running thrcads. In this section, we shall
class is used
Runnable interfacc to implement thrcads. sce how to make use of the
he Runnable interface declares thc run()
method that is
prograns. To do this, wc must pertonthe steps listed bclow: required for implementing thrcads in our
1 Declare the class as implementing the Runnable interface.
2 Implement the run() method.
1 Crcate a thrcad by defining an objcet that is
the thread.
instantiated from this "runnable class as the target of
4 Call the thrcad's start( ) method to runthe thrcad.
Program 12.4 illustrates the implcmcntation of the above steps. In main
method. we first create an
instance of N and then pass this instance as the initial value of the object threadX (an object of Thread
Class). I\henever. the new thread threadX starts up, its run() method calls the run( )
method of the target
obiect supplied to it. Here, the target object is runnable. If the direct reference to the thread threadX is not
required. thenwe nnay use a shortcut as shown below:
new Thread ( new X() ). start( )

Progranm 12.4 Using Runnable interface


class X implements Runnable // Step 1
public void run( ) 1/ Step 2
for (int i = l; i<=10; i++)

System.out.println ("\tThreadX +i) ;


}
System. out.println ("End of Threadx");

class RunnableTest

public static void main (String args( ])


2 runnable = new X()7
Thread threadx = new Thread( runnable); // Step3
threadX. start( ) i // Step 4
3ysten, out.println ("End of main Thread");

Output of Program 12.4:


End of main Thread
Threadx : 1
Threa d? : 2
ThreadX
Thread2
Thread2
ThreadX : 6
ThreadX
ThreadX : 8
Threadx :9
Progrannming with Java: A Primer
214

Thieaik : l0
End of Thread

12.11 INTER-THREAD COMMUNICATION


Inter-thread communication can be defined as the exchange of messages between two or more threads. The
transfer of messages takes place before or after the change of state of a thread. For example, an act
thread may notify to another suspended thread just before switching to the suspend state. Java implements
inter-thread communication with the help of following three methods:
notify(): Resumes the first thread that went into the sleep mode. The object class declaration of
notifv() method is shown below:
final void notify ()

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.

Suspending, Resuming and Stopping Thread


The functions of suspending, resuming and stopping a thread are performed using Boolean type tas
in amultithreading program. These flags store the current status of the thread. The run() method works
according to the current boolean value of these three flags. For instance, if the suspend flag is set to u
then run() will suspend the execution of the currently running thread. Similarly, if the resume flag s
to true then run() will resume the execution of the suspended thread. Apart from suspend and resuis
thread will get terminated once the stop flag of the thread is set to true.
Note: In Java 1., the suspend, resume and stop operations were performed using predefined.method
deprecacd
suspend(), resume() and stop() respectively. These three methods have beenmain reasoN
since the release of Java 2 and are not used in nodern Java progranming. The andsrstem
for deprecating these methods was to prevent the occurrence of deadlock situations
failures in a multi-threaded environment.

Program 12.5 llustration of suspend, resume and stop operations


class Sus res stop implements Runnable {

Thread Th;
boolean suspend flag, stop flag;
Multithreaded Programming 215

sus res stop (String tN) {


Th = new Thread(this, tN);
suspeni ilag = false;
stop fiag false;

Th.start0;

rubliC VOid run ()

int j=l;
while (++j<20)
í synchronized (this) {
while (suspend flag)
( wait();}

ii (stop flag)
break; }

catch (InterruptedException IE) {


System.out.println (" Thread interrupted");

synchronized void my suspend (){


suspend flag= true;

synchronized void my resume () {


suspend flag = false;
notify );
synchronized void my stop() {
Suspend flag = false;
stop flag = true;
notify():

public class eg SRS {


public static void main (String[] args)

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);

SRS T.ny resume () ;


RS T is resumed ");
System. out.println ("Thread S
Thread.sleep (2000) ;
216 Programming with Java: APrimer

SRS T.my suspend() ;


System. out.println ("Thread s R S T is suspended ")
Thread.sleep (2000) ;
SRS T.my resume ();
System.out.println ("Thread S RS T is resumed );
Thread.sleep(2000);
SRS T.my stop () ;
System. out.println("Thread S R S T is stopped ") ;

catch (InterruptedException IE) t


System. out.println ("Generated interrupted exception") ;

Output of the Program 12.5:


Thread SR ST is Created and started
Thread sR S T is suspended
Thread SRS T is resumed
Thread sRST is suspended
Thread SRS T is resumed
Thread SR S Tis stopped

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?

You might also like