Title: Universidad Nacional de Colombia
1C
ertificación en
J
AVA
- Universidad Nacional de Colombia
- Facultad de Ingeniería
- Departamento de Sistemas
27. THREADS
- Objectives
- Thread Fundamentals
- Controlling Threads
- Monitors, wait() and notify()
3Objectives
- Write code to define, instantiate, and start new
threads using - both java.lang.Thread and java.lang.Runnable
- Recognize conditions that might prevent a thread
from - executing
- Write code using synchronized, wait, notify, and
notifyAll - to protect against concurrent access problems and
to - communicate between threads. Define the
interaction - between threads and between threads and object
locks - when executing synchronized, wait, notify, or
notifyAll
4Introduction
5Thread fundamentals
Javas thread support resides in
- The Java.lang.Thread class
- The Java.lang.Object class
- The Java language and virtual machine
6A thread can be in various states At any
moment, at most one object is executing per CPU,
while others might be waiting for resources,
or waiting for a chance to execute, or
sleeping, or dead
7In order to understand threads, you need to be
able to answer these questions
- When a thread executes, what code does it
execute? - What states can a thread can be in?
- How does a thread changes its state?
8What a thread executes
thread scheduler determines which thread is
actually running on each available CPU at any
given time
9When a thread gets to execute, what does it
execute?
- The thread can execute its own run() method
- The thread can execute the run() method of some
other object
10Eventually the thread will execute, and at that
time its run() method will be called
11When you call the thread constructor, you have to
specify which object owns the run() method that
you want
The Runnable interface describes a single method
12Downcounter does not extend Thread, but it has a
run() method, and it declares that it implements
the Runnable interface
13Approaches to specifying which run() method will
be executed by a thread
14When execution ends
When the run() method returns, the thread has
finished its task and is considered dead Once a
thread is dead, it may not be started again A
dead thread continues to exist you can still
access its data and call its methods. You just
cannot make it run again!!
The thread methods include a method called
stop(), which forcibly terminates a thread,
putting it into the dead state
15If a thread might need to be killed from another
thread, you should send it an interrupt() from
the killing method!!!
16Thread states
When you call start() on a thread, it does not
run immediatley. It goes into a ready-to-run
state and stays there until the scheduler moves
it to the running state
- Thread states
- Running the states all threads aspire to
- Various waiting states
- waiting, sleeping, suspended, blocked
- Ready Not waiting for anything except
- the CPU
- Dead All done
17Living thread states
18Thread Priorities
Every thread has a priority, an integer from 1 to
10 threads with higher priority get preference
over threads with lower priority The priority is
considered by the thread scheduler when it
decides which ready thread should execute The
scheduler generally chooses the highest-priority
waiting thread. There is no guarantee that the
thread chosen will be the one that has been
waiting the longest
19- The default priority is 5, but all newly created
threads have their priority set to that of the
creating thread - setPriority() method to set a threads priority,
passing in the desired priority - getPriority() method returns a threads priority
20Controlling threads
The art of moving threads from state to state
Pathways out of the Running state
- Yielding
- Suspending and then resuming
- Sleeping and then waking up
- Blocking and then continuing
- the CPU
- Waiting and then being notified
21Yielding
A thread can offer to move out of the virtual CPU
by yielding A call to yield() method causes the
currently executing thread to move to the Ready
state
yield()
scheduled
22Yielding allows a time-consuming thread to permit
other threads to execute
The ray-tracing thread can have its priority set
like this
23(No Transcript)
24Suspending
allows any arbitrary thread to make another
thread un-runnable for an indefinite period of
time The suspended thread becomes runnable when
some other thread resumes it The effect of
suspend and resume is much better implemented
using wait and notify
25Sleeping
A sleeping thread passes time without doing
anything and without using the CPU
- public static void
- sleep(long milliseconds) throws
InterruptedException - public static void
- sleep(long milliseconds, int nanoseconds)
throws - InterruptedException
26The Sleeping state
A sleep call will block a thread for at least the
requested time, but it might block for much
longer A sleeping thread that receives an
interrupt() call moves immediately into the ready
state when it gets to run, it will execute its
interruptedException handler
27Blocking
Many methods that perform input or output have to
wait for some occurrence in the outside world
before they can proceed
Example Reading from a socket
28The Blocked State
29Monitor States
30Scheduling Implementations
- 1. Preemptive scheduling
- Ways for a thread to leave the running state
- It can cease to be ready to execute (e.g, by
calling a blocking I/O method) - It can get moved out of the CPU by a higher
priority thread that becomes ready to execute - 2. Time-sliced or round-robin scheduling
- A thread is only allowed to execute for a limited
amount of time
31Monitors, wait(), and notify
A monitor is an object that can block and revive
threads The reason for having monitors is that
sometimes a thread cannot perform its job until
an object reaches a certain state
32Example Handling requests to write to standard
output
A client can set a message to some value, then
set a request to true
33(No Transcript)
34- Javas monitor provides the following resources
- A lock for each object
- The synchronized keyword for accessing an
objects lock - The wait() , notify(), and notifyAll() methods,
which allow the object to control client threads
35The object lock and synchronization
Every object has a lock. At any moment, that lock
is controlled by, at most, one single thread. The
lock controls access to the objects synchronized
code A thread that wants to execute an objects
synchronized code must first attempt to acquire
that objects lock If the lock is under another
threads control, then the attempting thread goes
into the Seeking Lock state and only becomes
ready when the lock becomes available
36The Seeking lock State
37Ways to mark a code as synchronized Synchronize
an entire method by putting the synchronized
modifer in the methods declaration. To execute
the method, a thread must acquire the lock of the
object that owns the method Synchronize a subset
of the a method by surrounding the desired lines
of code with curly brackets () and inserting
the synchronized(someObject) expression before
the opening curly
38(No Transcript)
39wait() and notify()
Provide a way for a shared object to pause a
thread when it becomes unavailable to that
thread, and to allow the thread to continue when
appropriate The threads themselves never have to
check the state of the shared object An object
that controls its client threads in this manner
is known as a monitor Monitor any object that
has some synchronized code
40Both wait() and notify() must be called in
synchronized code A thread that calls wait
releases the virtual CPU at the same time, it
releases the lock. It enters a pool of waiting
threads, which is managed by the object whose
wait() method got called. Every object has such
a pool
41A message-consuming thread calling this method
42The Monitor States
Enter the synchronized code
wait
scheduled
notify() or notifyAll() timeout or interrupt
Lock obtained
43Revised storeMessage()
44(No Transcript)
45- Main points about wait()
- The calling thread gives up the CPU
- The calling thread gives up the lock
- The calling thread goes into the monitors
waiting pool
46- Main points about notify()
- One thread gets moved out of the monitors
waiting pool and into the Ready - The thread that was notified must re-acquire the
monitors lock before it can proceed
47Beyond the pure model
- The notify method is not precise
- You cannot specify which thread is to be notified
- A thread might alter the monitors state in a way
that is useless to the particular thread that
gets notified. - In such a case, the monitors methods should take
two precautions - Always check the monitors state in a while loop
rather than an if statement - After changing the monitors state, call
notifyAll() rather than notify()
48You should not do the following
49The solution is to change mixedUpMethod() as
follows
50Strange ways to synchronize
- Synchronizing on the lock of a different object
- Synchronizing on the lock of a class
51The following code synchronizes on the lock of
some arbitrary object
52To synchronize an entire method, using the lock
of the object that owns the method. Put the
synchronized keyword in the methods
declaration To synchronize part of a method,
using the lock of an arbitrary object. Put curly
brackets around the code to be synchronized,
preceded by synchronized(theArbitraryObject) To
synchronize part of a method, using the lock of
the object that owns that methods. Put curly
brackets around the code to be synchronized,
preceded by synchronized(this)