-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrw.real.mod.java
More file actions
87 lines (82 loc) · 1.98 KB
/
Copy pathrw.real.mod.java
File metadata and controls
87 lines (82 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Readers/Writers with concurrent read or exclusive write
//
// Usage:
// javac rw.real.java
// java Main rounds
import java.util.Random;
class RWbasic { // basic read or write
protected int data = 0; // the "database"
protected void read() {
System.out.println("read: " + data);
}
protected void write() {
data++;
System.out.println("wrote: " + data);
}
}
class ReadersWriters extends RWbasic { // Readers/Writers
int nr = 0;
private synchronized void startRead() {
nr++;
}
private synchronized void endRead() {
nr--;
if (nr==0) notify(); // awaken waiting Writers
}
public void read() {
startRead();
System.out.println("read: " + data);
endRead();
}
public synchronized void write() {
while (nr>0)
try { wait(); }
catch (InterruptedException ex) {return;}
data++;
System.out.println("wrote: " + data);
notify(); // awaken another waiting Writer
}
}
class Reader extends Thread {
int rounds;
ReadersWriters RW;
Random r = new Random();
public Reader(int rounds, ReadersWriters RW) {
this.rounds = rounds;
this.RW = RW;
}
public void run() {
for (int i = 0; i<rounds; i++) {
try {
sleep(r.nextInt(1000));
} catch (InterruptedException e) {};
RW.read();
}
}
}
class Writer extends Thread {
int rounds;
ReadersWriters RW;
Random r = new Random();
public Writer(int rounds, ReadersWriters RW) {
this.rounds = rounds;
this.RW = RW;
}
public void run() {
for (int i = 0; i<rounds; i++) {
try {
sleep(r.nextInt(1000));
} catch (InterruptedException e) {};
RW.write();
}
}
}
class Main { // driver program -- two readers and one writer
static ReadersWriters RW = new ReadersWriters();
public static void main(String[] arg) {
int rounds = Integer.parseInt(arg[0],10);
new Reader(rounds, RW).start();
new Reader(rounds, RW).start();
new Writer(rounds, RW).start();
}
}