SLIDE 9 Interface R/W
1 2
interface ReadWrite {
3 4
public void acquireRead ( ) throws InterruptedException ;
5 6
public void releaseRead ( ) ;
7 8
public void acquireWrite ( ) throws InterruptedException ;
9 10
public void releaseWrite ( ) ;
11
}
Reader client code
1 2
c l a s s Reader implements Runnable {
3 4
ReadWrite monitor_ ;
5 6
Reader( ReadWrite monitor ) {
7
monitor_ = monitor ;
8
}
9 10
p u b l i c void run ( ) {
11
try {
12
while ( true ) {
13
while ( ! ThreadPanel . r o t a t e ( ) ) ;
14
// begin c r i t i c a l s e c t i o n
15
monitor_ . acquireRead ( ) ;
16
while ( ThreadPanel . r o t a t e ( ) ) ;
17
monitor_ . releaseRead ( ) ;
18
}
19
} catch ( InterruptedException e ){}
20
}
21
}
Writer client code
1 2
c l a s s Writer implements Runnable {
3 4
ReadWrite monitor_ ;
5 6
Writer ( ReadWrite monitor ) {
7
monitor_ = monitor ;
8
}
9 10
p u b l i c void run ( ) {
11
try {
12
while ( true ) {
13
while ( ! ThreadPanel . r o t a t e ( ) ) ;
14
// begin c r i t i c a l s e c t i o n
15
monitor_ . acquireWrite ( ) ;
16
while ( ThreadPanel . r o t a t e ( ) ) ;
17
monitor_ . r e l e a s e W r i t e ( ) ;
18
}
19
} catch ( InterruptedException e ){}
20
}
21
}
R/W monitor (regulate readers)
1 2
c l a s s ReadWriteSafe implements ReadWrite {
3
p r i v a t e int r e a d e r s =0;
4
p r i v a t e boolean w r i t i n g = f a l s e ;
5 6
p u b l i c synchronized void acquireRead ( )
7
throws InterruptedException {
8
while ( w r i t i n g ) wait ( ) ;
9
++r e a d e r s ;
10
}
11 12
p u b l i c synchronized void releaseRead ( ) {
13
− −r e a d e r s ;
14
i f ( r e a d e r s==0) notifyAll ( ) ;
15
}
16 17
p u b l i c synchronized void acquireWrite ( ) { . . . }
18 19
p u b l i c synchronized void r e l e a s e W r i t e ( ) { . . . }
20
}
9