Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Agenda

1 synchronised keyword I
2 Synchronised methods
I
Problem start
3 Semaphores Producer Consumer
4 Atomic Data Types
Synchronised keyword specific to java

count implicit lock property

Adder Subtractor
paint Hello
Hi
print count synchronized count
synchronized
Read count
Read want
is
x 1
x 1
count count

prints Bye print Bye

think like
count count lock lock
synchronised

Critical section
code

I count lock unlock


Synchronized methods
a class
synchronized only 1 thread
as
If you declare a
ofmethod
synchronized method of that object at 1 time
can be in any
class count
1.1 value
private int
synchronised void increment value C
decrement Value 1
synchronised void
C
getvalue

Count 4 new count


e.g
Count 2 new count

T2 will they run in parallel


M
No
11inevaluel
G incvalue
No
Cl incvalue A devalue 1
Yes
Cl getValue 1 1 is not a
cl.in value getvalue Shahody
objects
C2 incvalueC
Yes Diff
Clinevaluel
Yes Diff objects
1 invaluell 2 devalue 1
Synchronized methods are a way to prevent client from handling
concurrency
How threads allowed to enter is at one time 1
many

Éfgfhfhffh fÉ i

mnᵈfʰ

EL

9 Consumers shirts
If Buy

conditions
to enter the showroom if there is a
1 I only want a consumer
shirt available for
them
the showroom if there is
want to enter
2 I only a
producer
them to put their shirt
space
available for
empty spaces
that can enter the store
producers
enter the store filled spaces
consumers that can

Situation we need to write code for this producer consumer


interaction
hist Robert store
int maxsize 6

Consumer
Produce
store size 1 0 E
if
store size1 mansize if
store remove
store.add newshirts

Infront
smario

Producer T2 Producer 2
sickman True
ifsinehmax I.de if
11 Ff critical section

How do we solve this ILK


solution using hocks
P1 P2

queue

enter the CS
At one time only 1 person is allowed to
Because of how a lock works
Why
No
Is thisgoing to lead synchronization problem
to
It will
week
Not fast enough
Semaphores

Muted with upperbound 71

s new semaphore
Semaphore 1
This means at mar 2
the
threads can acquire
look at 1 time

Semaphores now semaphore


1
Nuts
queue
store I consumer
Producer common
semaphores

g acquire g acquire C
stoma add items store remove
5 release g release

In Semaphore
In winter
lock Semaphore
lockl s acquire 11
s release 1
unlock I
9H
If massive 7
enter because 4 shirts
4 consumers can
Semaphore
s new semaphore 14

a
THE
dET
Inum
store FIT All empty

semaphore
new semaphore
consumer that can enter 7
C 1 0
Semaphore
p 4
3 7
Semaphore

Producer store If consumer

c acquired
prequire store remove
CS
store addlitem
c releaselli prelease

a Integers t locks
to think of semaphores
Try

fÉfÉ
tfhhhhhhfhtdhd
ffhfn.fm

ffÉÉiTÉÉ f

f Hra 00

HIM Coffemaphores

You might also like