Multithreading
Chapter 23
2
Introduction
• Consider ability of human body to ___________– Breathing, heartbeat, chew gum, walk …
• In many situations we need a computer to multitask
• Concurrency normally available in __________
• Java provides built-in multithreading– Multithreading improves the ___________ of some
programs
3
Thread States: Life Cycle of a Thread
• __________________ state– New thread begins its life cycle in the new state– Remains in this state until program starts the
thread, placing it in the runnable state
• runnable state– A thread in this state is ___________ its task
• waiting state– A thread ___________ to this state to wait for
another thread to perform a task
4
Thread States: Life Cycle of a Thread
• __________________ state– A thread enters this state to wait for another
thread or for an amount of time to elapse– A thread in this state returns to the ___________
state when it is signaled by another thread or when the timed interval expires
• terminated state– A runnable thread enters this state when it
_____________ its task
5
Operating System View Of runnable State
• ready state– ____________ waiting for another thread– Waiting for the ______________ to assign the
thread a processor
6
Operating System View Of runnable State
• running state– Currently has a _________________ and is
executing– Often executes for a small amount of processor
time called a _______________________ before transitioning back to the ready state
7
Thread Priorities and Thread Scheduling
• Java thread priority– Priority in range ______________
• Timeslicing– Each thread assigned time on the processor (called
a quantum)– Keeps ______________ threads running
8
Priorities and
Scheduling
Thread.MAX_PRIORITY
9
Creating and Executing Threads•Runnable interface
– Preferred means of creating a multithreaded application
– Declares method _______________– Executed by an object that implements the Executor interface
•Executor interface– Declares method ___________________– Creates and manages a group of threads called
a thread pool
10
Creating and Executing Threads
•ExecutorService interface– ______________________ of Executor that
declares other methods for managing the life cycle of an Executor
– Can be created using _______________ methods of class Executors
– Method shutdown _______________ when tasks are completed
11
Creating and Executing Threads
•Executors class– Method newFixedThreadPool creates a pool
consisting of a __________________________ of threads
– Method newCachedThreadPool creates a pool that creates new threads _____________________________
12
Creating and Executing Threads
• PrintTask class Figure 23.4
• RunnableTester, Figure 23.5
• Demonstrates– ____________ Thread objects– Using Thread methods ___________ and sleep– Creates 3 equal priority threads– Each is put to sleep for random number of
milliseconds– When awakened, it displays name, etc.
13
Producers and Consumers
• Producer– Generating
_______________
• Consumer– Receives and
_________________the output
14
Synchronization
• Problem– Sometimes the producer gets too far
____________ of the consumer • The objects produced fill up the holding area
(_____________)• The producer must wait for space to place objects
– Sometimes the ______________ gets ahead of the producer
• There are no objects to be processed (_____________ buffer)
• The consumer must wait for the producer
15
Thread Synchronization• Thread synchronization
– Provided to the programmer with _____________________• Exclusive access to a shared object
– Implemented in Java using _____________
•Lock interface– lock method obtains the lock, enforcing mutual
exclusion– unlock method ________________ the lock– Class ReentrantLock implements the Lock
interface
16
Thread Synchronization
• Condition variables– If a thread holding the lock cannot continue with its
task until a condition is satisfied, the thread can wait on a ____________________
– Create by calling Lock method newCondition– Represented by an object that implements the ___________________ interface
17
Thread Synchronization
• Condition interface– Declares methods await, to make a thread wait, – ____________________, to wake up a waiting
thread, and – signalAll, to wake up all waiting threads
18
Producer/Consumer Relationship without Synchronization
• Buffer– ____________________ memory region
• Producer thread– Generates _____________ to add to buffer– Calls wait if consumer has not read previous message in
buffer– Writes to empty buffer and calls ____________ for
consumer
• Consumer thread– Reads data from buffer– Calls wait if buffer ________________
• Synchronize threads to avoid corrupted data
19
Producer/Consumer Relationship without Synchronization
• View source code which establishes– Buffer, Figure 23.6
• An interface which specifies get and set methods
– Producer, Figure 23.7• ___________________ of Thread• Uses a shared Buffer object• Method run is _________________ from Thread class• Uses Buffer.set() method
– Consumer, Figure 23.8• Also a subclass of Thread, also uses shared Buffer• Uses the Buffer.get() method
20
Producer/Consumer Relationship without Synchronization
• View Figure 23.9 which implements the Buffer interface– Implements the _________________ methods
• This UnsynchronizedBuffer object is used in Figure 23.10 program– Buffer object declared, instantiated– Also Producer and Consumer objects– Both threads call method start()
21
Producer/Consumer Relationship without Synchronization
• Example randomly called producer and consumer
• You should note that in some cases the data was _________________– Consumer reads values _________ producer
generates– Consumer _______________ a value– Consumer reads same value multiple times
• We need to deal with problem so data is not corrupted
22
Producer/Consumer Relationship with Synchronization
• Solution is to _________________ the producer and consumer objects
• Figure 23.11 implements a buffer and synchronizes – Consumer consumes only ______ produces a value– Producer produces a value only after consumer
consumes ____________ value produced– Condition variable occupiedBufferCount
determines whose turn it is
• Program which uses this, Figure 23.12
23
Using Thread Methods
• Create Wait class
• Has _______________ methods
• Provide capability to have another application ______________ for a certain amount of time
• Note Example to act as a simple timer.
24
Circular Buffer• Features
– Multiple memory cells– Produce item if one or more empty cells– Consume item if one or more filled cells
• Caveats– Producer and consumers must be relatively
______________ speed• Otherwise buffer fills up or stays empty
– Synchronization still necessary– Seek to optimize buffer size
• ______________________ thread-wait time
25
Circular Buffer
• Circular Buffer class Figure 23.13– ______________ for mutual exclusion– Condition variables to control writing and reading– Circular buffer; provides three spaces for data– Obtain the lock ____________ writing data to the
circular buffer– Wait until a buffer space is ___________– Impose circularity of the buffer– ___________ waiting thread when to read data
from buffer– Release lock
26
Circular Buffer
• Circular Buffer test, Figure 23.14– Create instance of circular buffer– Execute producer, consumer in separate threads
27
Daemon Threads
• Run for benefit of _____________________– Do not prevent program from terminating– __________________ is a daemon thread
• Set daemon thread with method setDaemon– Must be done at __________________ time
• Do not assign _____________ tasks to daemon thread– Will be terminated without warning– May prevent those tasks from completing properly
28
Runnable Interface
• May be necessary to __________ a class that already extends a class other than Thread
• Java does not allow a class to extend more than one class at a time– Implement Runnable for ____________ support
• Program that uses a Runnable object to control a thread– Creates a Thread object– Associates the Runnable object with that Thread
class
29
Runnable Interface
• Illustration of using a Runnable interface– Figure 23.18
• Note methods start, stop, run