0% found this document useful (0 votes)
5 views68 pages

Module 5 - Threads-1

The document discusses multithreaded programming in Java, explaining how it allows multiple threads to run concurrently, enhancing efficiency compared to process-based multitasking. It covers the Java Thread model, thread states, priorities, and methods for creating and managing threads, including the use of the Thread class and Runnable interface. Key concepts such as context switching, thread blocking, and the main thread's role in execution are also highlighted.

Uploaded by

nithishkumarm106
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)
5 views68 pages

Module 5 - Threads-1

The document discusses multithreaded programming in Java, explaining how it allows multiple threads to run concurrently, enhancing efficiency compared to process-based multitasking. It covers the Java Thread model, thread states, priorities, and methods for creating and managing threads, including the use of the Thread class and Runnable interface. Key concepts such as context switching, thread blocking, and the main thread's role in execution are also highlighted.

Uploaded by

nithishkumarm106
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

MAHARAJA INSTITUTE OF TECHNOLOGY MYSORE

DEPARTMENT OF COMPUTER SCIENCE AND


BUSINESS SYSTEM

3rd Semester
“Object Oriented Programming with Java”
M23BCS306B

Staff Name:
Module 5: Dr. Honnaraju B
Threads Associate. Prof. and Head
Dept. of CS&BS
MIT Mysore
1
Multithreaded Programming:
❑ Java provides built-in support for multithreaded
M programming. A multithreaded program contains two or
more parts that can run concurrently.
I
❑ Each part of such a program is called a thread, and each
T thread defines a separate path of execution. Thus,
multithreading is a specialized form of multitasking.

M ❑ There are two distinct types of multitasking: process-


based and thread-based. It is important to understand the
y difference between the two.
s
❑ For many readers, process-based multitasking is the more
o familiar form. A process is, in essence, a program that is
executing.
r
e ❑ Thus, process-based multitasking is the feature that
allows your computer to run two or more programs
concurrently.
Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 2
❑ In a thread-based multitasking environment, the thread is
the smallest unit of dispatchable code.
M
❑ This means that a single program can perform two or
I more tasks simultaneously.
T ❑ For instance, a text editor can format text at the same
time that it is printing, as long as these two actions are
being performed by two separate threads.
M ❑ Thus, process-based multitasking deals with the “big
picture,” and thread-based multitasking handles the
y details.
s ❑ Multitasking threads require less overhead than
o multitasking processes.

r ❑ Processes are heavyweight tasks that require their own


separate address spaces.
e ❑ Interprocess communication is expensive and limited.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 3


M ❑ Context switching from one process to another is also costly.

I ❑ Threads, on the other hand, are lighter weight.


T ❑ They share the same address space and cooperatively
share the same heavyweight process.
❑ Inter-thread communication is inexpensive, and context
M switching from one thread to the next is lower in cost.
y
❑ While Java programs make use of process-based
s multitasking environments, process-based multitasking
is not under Java’s direct control.
o
r ❑ However, multithreaded multitasking is.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 4


The Java Thread Model :
❑ The Java run-time system depends on threads for many
M things, and all the class libraries are designed with
multithreading in mind.
I ❑ In fact, Java uses threads to enable the entire
T environment to be asynchronous. This helps reduce
inefficiency by preventing the waste of CPU cycles.
❑ The value of a multithreaded environment is best
M understood in contrast to its counterpart.
y ❑ Single-threaded systems use an approach called an event
loop with polling.
s
❑ In this model, a single thread of control runs in an infinite
o loop, polling a single event queue to decide what to do
next.
r
❑ Once this polling mechanism returns with, say, a signal
e that a network file is ready to be read, then the event
loop dispatches control to the appropriate event handler.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 5


❑ In general, in a single-threaded environment, when a
thread blocks (that is, suspends execution) because it is
M waiting for some resource, the entire program stops
running.
I ❑ The benefit of Java’s multithreading is that the main
T loop/polling mechanism is eliminated.
❑ One thread can pause without stopping other parts of
your program.
M
❑ For example, the idle time created when a thread reads
y data from a network or waits for user input can be
utilized elsewhere.
s
❑ Multithreading allows animation loops to sleep for a
o second between each frame without causing the whole
r system to pause.
❑ When a thread blocks in a Java program, only the single
e thread that is blocked pauses. All other threads continue
to run.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 6


States of a Thread:
M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 7


Threads exist in several states.
M Here is a general description.
I ❖ A thread can be running.
❖ It can be ready to run as soon as it gets CPU time.
T ❖ A running thread can be suspended, which temporarily
halts its activity.
❖ A suspended thread can then be resumed, allowing it to
M pick up where it left off.
❖ A thread can be blocked when waiting for a resource.
y ❖ At any time, a thread can be terminated, which halts its
execution immediately. Once terminated, a thread cannot
s be resumed.
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 8


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 9


M Thread Priorities:
❑ Java assigns to each thread a priority that determines how
I that thread should be treated with respect to the others.
T ❑ Thread priorities are integers that specify the relative
priority of one thread to another.
❑ As an absolute value, a priority is meaningless; a higher-
M priority thread doesn’t run any faster than a lower-
y priority thread if it is the only thread running.

s ❑ Instead, a thread’s priority is used to decide when to


switch from one running thread to the next. This is
o called a context switch.
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 10


The rules that determine when a context switch takes place
M are simple:

I ❖ A thread can voluntarily relinquish control. This


occurs when explicitly yielding, sleeping, or when
T blocked. In this scenario, all other threads are examined,
and the highest-priority thread that is ready to run is
given the CPU.
M
❖ A thread can be preempted by a higher-priority
y thread. In this case, a lower-priority thread that does not
s yield the processor is simply preempted—no matter
what it is doing—by a higher-priority thread. Basically,
o as soon as a higher-priority thread wants to run, it does.
This is called preemptive multitasking.
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 11


The Thread Class and the Runnable Interface:
❑ Java’s multithreading system is built upon the Thread
M class, its methods, and its companion interface,
Runnable.
I
T ❑ Thread encapsulates a thread of execution. Since you
can’t directly refer to the ethereal state of a running
thread, you will deal with it through its proxy, the
Thread instance that spawned it.
M
y ❑ To create a new thread, your program will either extend
Thread or implement the Runnable interface.
s
❑ The Thread class defines several methods that help
o manage threads.
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 12


M
I Method Meaning
getName Obtain a thread’s name.
T getPriority Obtain a thread’s priority.
isAlive Determine if a thread is still running.
join Wait for a thread to terminate.
M run Entry point for the thread.
sleep Suspend a thread for a period of time.
y start Start a thread by calling its run method.
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 13


The Main Thread:
M When a Java program starts up, one thread begins running
I immediately.

T This is usually called the main thread of your program,


because it is the one that is executed when your program
begins.
M
The main thread is important for two reasons:
y ❑ It is the thread from which other “child” threads will be
spawned.
s
❑ Often, it must be the last thread to finish execution
o because it performs various shutdown actions.
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 14


❑ Although the main thread is created automatically when
your program is started, it can be controlled through a
M Thread object.
I
❑ To do so, you must obtain a reference to it by calling the
T method currentThread( ), which is a public static member
of Thread. Its general form is shown here:
static Thread currentThread( )
M
❑ This method returns a reference to the thread in which
y it is called. Once you have a reference to the main thread,
you can control it just like any other thread.
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 15


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 16


The sleep( ) method causes the thread from which it is called
to suspend execution for the specified period of milliseconds.
M Its general form is shown here:
I static void sleep(long milliseconds) throws
InterruptedException
T The number of milliseconds to suspend is specified in
milliseconds. This method may throw an
InterruptedException.
M
The sleep( ) method has a second form, shown next, which
y allows you to specify the period in terms of milliseconds
and nanoseconds:
s
static void sleep(long milliseconds, int nanoseconds)
o throws InterruptedException
r
This second form is useful only in environments that allow
e timing periods as short as nanoseconds.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 17


❑ You can obtain the name of a thread by calling getName( )
M (but note that this is not shown in the program).

I ❑ These methods are members of the Thread class and are


declared like this:
T
final void setName(String threadName)
final String getName()
M
❑ Here, threadName specifies the name of the thread.
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 18


M
I
T
Creating a Thread:
In the most general sense, we create a thread by initiating an
M object of type Thread.
Java defines two ways in which this can be accomplished:
y 1. You can implement the Runnable interface.
s 2. You can extend the Thread class, itself.

o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 19


Implementing Runnable:
❑ The easiest way to create a thread is to create a class that
M implements the Runnable interface.
I ❑ Runnable abstracts a unit of executable code. You can
T construct a thread on any object that implements
Runnable.
❑ To implement Runnable, a class need only implement a
M single method called run( ), which is declared like this:
public void run()
y
❑ Inside run( ), you will define the code that constitutes the
s new thread. It is important to understand that run( ) can
call other methods, use other classes, and declare
o variables, just like the main thread can.
r ❑ The only difference is that run( ) establishes the entry
e point for another, concurrent thread of execution within
your program. This thread will end when run( ) returns.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 20


❑ After you create a class that implements Runnable, you
will declare an object of type Thread from within that
M class.
I ❑ Thread defines several constructors. The one that we will
use is shown here:
T Thread(Runnable threadOb, String threadName)

❑ In this constructor, threadOb is an instance of a class that


M implements the Runnable interface. This defines where
execution of the thread will begin.
y
s The name of the new thread is specified by threadName.

o ❑ After the new thread is created, it will not start running


r until you call its start( ) method, which is declared within
Thread. In essence, start( ) initiates a call to run( ). The
e start( ) method is shown here:
void start( )

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 21


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 22


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 23


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 24


Extending Thread
The second way to create a thread is to create a new class that
M extends Thread, and then to create an instance of that class.

I The extending class must override the run( ) method, which is the
entry point for the new thread.
T
It must also call start( ) to begin execution of the new thread. Here
is the preceding program rewritten to extend Thread:
M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 25


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 26


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 27


Creating Multiple Threads

M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 28


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 29


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 30


Using isAlive( ) and join( )
▪ How can one thread know when another thread has ended?
M Fortunately, Thread provides a means by which you can answer
this question.
I Two ways exist to determine whether a thread has finished.
❑ First, you can call isAlive( ) on the thread. This method is defined
T by Thread, and its general form is shown here:
final boolean isAlive( )
The isAlive( ) method returns true if the thread upon which it is
called is still running. It returns false otherwise.
M
y While isAlive( ) is occasionally useful, the method that you will more
commonly use to wait for a thread to finish is called join( ), shown
s here:
final void join( ) throws InterruptedException
o
This method waits until the thread on which it is called
r terminates. Its name comes from the concept of the calling thread
waiting until the specified thread joins it. Additional forms of join( )
e allow you to specify a maximum amount of time that you want to
wait for the specified thread to terminate.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 31


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 32


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 33


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 34


Thread Priorities
❑ Thread priorities are used by the thread scheduler to decide
M when each thread should be allowed to run.

I ❑ In theory, over a given period of time, higher-priority threads


get more CPU time than lower-priority threads.
T
❑ In practice, the amount of CPU time that a thread gets often
depends on several factors besides its priority. (For example,
M how an operating system implements multitasking can affect the
relative availability of CPU time.)
y
❑ A higher-priority thread can also preempt a lower-priority
s one.
o ❑ For instance, when a lower-priority thread is running and a
higher-priority thread resumes (from sleeping or waiting on I/O,
r for example), it will preempt the lower-priority thread.
e
❑ In theory, threads of equal priority should get equal access to the
CPU.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 35


M To set a thread’s priority, use the setPriority( ) method, which is a
member of Thread. This is its general form:
I
final void setPriority(int level)
T
Here, level specifies the new priority setting for the calling thread.
The value of level must be within the range MIN_PRIORITY and
M MAX_PRIORITY.
Currently, these values are 1 and 10, respectively. To return a
y thread to default priority, specify NORM_PRIORITY, which is
currently 5.
s
These priorities are defined as static final variables within Thread.
o You can obtain the current priority setting by calling the
getPriority( ) method of Thread, shown here:
r final int getPriority( )
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 36


Synchronization
When two or more threads need access to a shared resource,
M they need some way to ensure that the resource will be used by
only one thread at a time.
I The process by which this is achieved is called synchronization.
T As you will see, Java provides unique, language-level support for
it.
Key to synchronization is the concept of the monitor. A
monitor is an object that is used as a mutually exclusive lock.
M
Only one thread can own a monitor at a given time. When a
y thread acquires a lock, it is said to have entered the monitor.
s All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor.
o
These other threads are said to be waiting for the monitor. A
r thread that owns a monitor can reenter the same monitor if it so
desires.
e
You can synchronize your code in either of two ways. Both involve
the use of the synchronized keyword, and both are examined here.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 37


M
I
T

M
y
s
o
r
e
Figure: Monitor with condition variables.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 38


M Using Synchronized Methods
❑ Synchronization is easy in Java, because all objects have their
I own implicit monitor associated with them.

T ❑ To enter an object’s monitor, just call a method that has been


modified with the synchronized keyword.

❑ While a thread is inside a synchronized method, all other


M threads that try to call it (or any other synchronized method) on
y the same instance have to wait.

s ❑ To exit the monitor and relinquish control of the object to the


next waiting thread, the owner of the monitor simply returns
o from the synchronized method.

r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 39


❑ The first one, Callme, has a single method named call( ). The call(
) method takes a String parameter called msg.

M ❑ This method tries to print the msg string inside of square brackets.

I ❑ The interesting thing to notice is that after call( ) prints the


opening bracket and the msg string, it calls [Link](1000),
T which pauses the current thread for one second.

❑ The constructor of the next class, Caller, takes a reference to an


M instance of the Callme class and a String, which are stored in
target and msg, respectively.
y
❑ The constructor also creates a new thread that will call this
s object’s run( ) method. The thread is started immediately.
o ❑ The run( ) method of Caller calls the call( ) method on the target
instance of Callme, passing in the msg string. Finally, the Synch
r class starts by creating a single instance of Callme, and three
e instances of Caller, each with a unique message string. The same
instance of Callme is passed to each Caller.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 40


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 41


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 42


The synchronized Statement
❑ While creating synchronized methods within classes that you
M create is an easy and effective means of achieving
synchronization, it will not work in all cases.
I
❑ To understand why, consider the following. Imagine that you
T want to synchronize access to objects of a class that was not
designed for multithreaded access. That is, the class does not use
synchronized methods.
M
❑ Further, this class was not created by you, but by a third party,
y and you do not have access to the source code.

s ❑ Thus, you can’t add synchronized to the appropriate methods


within the class.
o
❑ How can access to an object of this class be synchronized?
r Fortunately, the solution to this problem is quite easy: You
e simply put calls to the methods defined by this class inside a
synchronized block.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 43


M
This is the general form of the synchronized statement:
I synchronized(objRef)
{
T // statements to be synchronized
}

M ❑ Here, objRef is a reference to the object being synchronized.

y ❑ A synchronized block ensures that a call to a synchronized


method that is a member of objRef’s class occurs only after the
s current thread has successfully entered objRef’s monitor.
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 44


Here is an alternative version of the preceding example, using a
synchronized block within the run( ) method:

M // This program uses a synchronized block.


class Callme
I {
void call(String msg)
T {
[Link]("[" + msg);
try
M {
[Link](1000);
y }
catch (InterruptedException e)
s {
[Link]("Interrupted");
o }
[Link]("]");
r }
e }

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 45


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 46


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 47


Inter-thread Communication
❑ Multithreading replaces event loop programming by dividing
your tasks into discrete, logical units.
M
❑ Threads also provide a secondary benefit: they do away with
I polling. Polling is usually implemented by a loop that is used to
check some condition repeatedly.
T
❑ Once the condition is true, appropriate action is taken. This
wastes CPU time.
M ❑ For example, consider the classic queuing problem, where one
thread is producing some data and another is consuming it.
y
❑ To make the problem more interesting, suppose that the producer
s has to wait until the consumer is finished before it generates
more data.
o ❑ In a polling system, the consumer would waste many CPU
r cycles while it waited for the producer to produce.
❑ Once the producer was finished, it would start polling, wasting
e more CPU cycles waiting for the consumer to finish, and so
on. Clearly, this situation is undesirable.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 48


To avoid polling, Java includes an elegant interprocess
communication mechanism via the wait( ), notify( ), and notifyAll( )
M methods.

I These methods are implemented as final methods in Object, so all


classes have them.
T
All three methods can be called only from within a synchronized
context.
M Although conceptually advanced from a computer science
y perspective, the rules for using these methods are actually quite
simple:
s ❑ wait( ) tells the calling thread to give up the monitor and go to
sleep until some other thread enters the same monitor and calls
o notify( ) or notifyAll( ).

r ❑ notify( ) wakes up a thread that called wait( ) on the same object.


e ❑ notifyAll( ) wakes up all the threads that called wait( ) on the
same object. One of the threads will be granted access.

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 49


These methods are declared within Object, as shown here:
❑ final void wait( ) throws InterruptedException
M ❑ final void notify( )
❑ final void notify All( )
I
Additional forms of wait( ) exist that allow you to specify a period of
T time to wait.

Before working through an example that illustrates interthread


M communication, an important point needs to be made.

y Although wait( ) normally waits until notify( ) or notifyAll( ) is


called, there is a possibility that in very rare cases the waiting
s thread could be awakened due to a spurious wakeup.

o In this case, a waiting thread resumes without notify( ) or


notifyAll( ) having been called.
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 50


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 51


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 52


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 53


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 54


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 55


Deadlock
❑ A special type of error that you need to avoid that relates
specifically to multitasking is deadlock, which occurs when
M two threads have a circular dependency on a pair of
synchronized objects.
I
❑ For example, suppose one thread enters the monitor on object
T X and another thread enters the monitor on object Y. If the
thread in X tries to call any synchronized method on Y, it will
block as expected.
M
❑ However, if the thread in Y, in turn, tries to call any
y synchronized method on X, the thread waits forever, because to
access X, it would have to release its own lock on Y so that
s the first thread could complete.
o ❑ Deadlock is a difficult error to debug for two reasons:
r • In general, it occurs only rarely, when the two threads time-slice in
just the right way.
e • It may involve more than two threads and two synchronized
objects. (That is, deadlock can occur through a more convoluted
sequence of events than just described.)

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 56


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 57


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 58


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 59


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 60


M
I Suspending, Resuming, and Stopping Threads
❑ Sometimes, suspending execution of a thread is useful.
T
❑ For example, a separate thread can be used to display the time of
day.
M ❑ If the user doesn’t want a clock, then its thread can be
y suspended.

s ❑ A program used suspend( ), resume( ), and stop( ), which are


methods defined by Thread, to pause, restart, and stop the
o execution of a thread.

r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 61


❑ The resume( ) method is also deprecated. It does not cause
M problems, but cannot be used without the suspend( ) method as
its counterpart.
I
❑ The stop( ) method of the Thread class, too, was deprecated by
T Java 2. This was done because this method can sometimes cause
serious system failures.

M ❑ Assume that a thread is writing to a critically important data


structure and has completed only part of its changes.
y
❑ If that thread is stopped at that point, that data structure might
s be left in a corrupted state.

o ❑ The trouble is that stop( ) causes any lock the calling thread
holds to be released. Thus, the corrupted data might be used by
r another thread that is waiting on the same lock.
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 62


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 63


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 64


M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 65


Obtaining a Thread’s State
A thread can exist in a number of different states. You can obtain
the current state of a thread by calling the getState( ) method
M defined by Thread. It is shown here:
I [Link] getState( )
It returns a value of type [Link] that indicates the state of the
T thread at the time at which the call was made.
State is an enumeration defined by Thread.
M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 66


Figure below show the various thread states relate.
M
I
T

M
y
s
o
r
e

Dr. Honnaraju B, Dept. of CS&BS, MIT Mysore 67


M
I
T

M
y
s
o
r
e

You might also like