Professional Documents
Culture Documents
Threads 1
What is a Thread?
Why multi-thread?
Threads 2
Problems with multithreading
Example:
• Two workers can speak only if one speaks and the other listens
• A worker cannot use the copy machine until the machine is free
• For two threads to communicate - one has to talk and the other has to listen
• For a thread to use a shared resources, the resource has to be free and ready
Threads 3
Problems with multithreading
The Cooperative threading and Preemptive threading model
copier
copier
start copying
start copying
C pause copying
o P
start copying
o r
p done copying e
pause copying
e e
r m
restart copying
a start copying p
t t
pause copying
i i
start copying
v v
e done copying
e
pause copying
start copying
done copying
Threads 4
How do you make a class run in its own thread?
• extend Thread, or
• implement Runnable
Extending Thread
start
ready
yield assigned a
processor
IO complete
done waiting running
notify
or notifyAll
doing IO
wait
sleep complete
Threads 8
Synchronizing execution between two threads
Understanding the problem
Assume a simple BankAccount class.
Electronic pay
ATM
transaction
What would happen if these actions
could happen in parallel? Would the
Threads 9
account balance be correctly maintained?
Synchronizing execution between two threads
Solution - To “lock” methods so that only one thread can execute that method
public class BankAccount{
String holderName; paused
float amount;
and waiting
public Account(String n, float a){
their turn
holderName = n;
amount = a;
}
public synchronized void deposit(float a){
amount = amount + a;
}
public synchronized void withdraw(float a){
amount = amount - a;
}
public float checkBalance(){
return amount;
Locked
} Method
}
Notice: checkBalance() not synchronized one thread
allowed through
at a time
Threads 10
Synchronizing execution between two threads
An object with a synchronized method will only allow one thread at a time to
execute a synchronized method. Such an object is called a Monitor
If there are many synchronized methods only one synchronized method may be active
on an object at once; all other threads attempting to invoke synchronized methods
must wait.
Thread 2 can only run unsynchronized methods of the Monitor while Thread 1 is
running a synchronized method.
Threads 11
The (classic) producer-consumer example
3-classes:
The “producer” produces an integer to be consumed by the “consumer”. The
produced value is held in a common shared cell.
Rules:
Producer Consumer
• Consumer may consume an integer once
integer • Consumer may not consume until the producer has produced
Threads 14
The producer-consumer example
public class SharedCellSynchronizedI{
private int shared = -1;
public synchronized void set(int i){
System.out.println(“producer producing “+ i);
shared = i;
}
public synchronized int get(){
System.out.println(“Consumer consuming “+shared);
return shared;
}
}
Threads 15
The producer-consumer example
Create a boolean variable consumerHasConsumed
Initialize consumerHasConsumed to true
Producer (set()) Consumer (get())
If (consumerHasComsumed is false) If (consumerHasConsumed is true)
producer will “wait” consumer will “wait”
else else
producer will produce consumer will consume
set consumerHasConsumed to false set consumerHasConsumed to true
public class SharedCellSynchronizedII{
private int shared = -1;
boolean consumerHasConsumed
Summary:
• Two independent threads work with a common object
• Both threads “own” the common object (not threaded)
• Because of method synchronization only one thread can
execute on the object at a time
• Both threads voluntarily give up owner ship by “waiting”
• Common object coordinates the common activity.
Threads 17
wait verses sleep - which to use? What’s the difference?
•Sleeping threads sleep the whole duration or till its interrupted. Use sleep/interrupt if
you want to control when a thread runs.
• Both sleep() and wait() give up contending for the CPU, even if the thread is in a
synchronized method.
• To use wait(), the current thread must own the objects monitor.
Huh?
Threads 18
Modeling a Train, track and a crossing using threads
Classes and interactions:
Track - not threaded has a crossing, and keeps track of the train position
Crossing arm (threaded) - lowers and raises the arm based on a signal from the track
The Train:
Threads 21
Deadlocking
What happens?
• Thread 1 gets the lock for resource 1 and waits on resource 2
• Thread 2 gets the lock for resource 2 and waits on 1
• Neither thread now can continue because the other thread has a critical lock
Classic Example:
• Dinners problem
• Imagine two people at dinner having to share a knife and fork
• Person 1 has gets the knife and person 2 the fork - now neither can eat.
(more general problem called Dinning philosophers problem…)
Threads 22
Deadlocking - what’s the solution?
Threads 23