-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadersWriters.java
More file actions
75 lines (62 loc) · 2.09 KB
/
Copy pathReadersWriters.java
File metadata and controls
75 lines (62 loc) · 2.09 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
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReadersWriters {
boolean writer = false;
int readers = 0;
boolean wantToWrite = false;
public synchronized void ReaderLock() throws InterruptedException{
while(writer || wantToWrite){
wait();
}
readers++;
}
public synchronized void ReaderUnlock() throws InterruptedException{
readers--;
if(readers==0){
notifyAll();
}
}
public synchronized void WriterLock() throws InterruptedException{
wantToWrite = true;
while(readers > 0 || writer){
wait();
}
writer = true;
wantToWrite = false;
}
public synchronized void WriterUnlock() throws InterruptedException{
writer=false;
notifyAll();
}
public ReadersWriters() {
final int numReadersWriters = 10;
for (int i = 0; i < numReadersWriters; i++) {
new Thread(() -> {
try{
ReaderLock();
System.out.println(" Reader " + Thread.currentThread().getId() + " started reading");
// read
System.out.println(" Reader " + Thread.currentThread().getId() + " stopped reading");
ReaderUnlock();
}catch(InterruptedException e){
System.out.println(e);
}
}).start();
new Thread(() -> {
try{
WriterLock();
System.out.println(" Writer " + Thread.currentThread().getId() + " started writing");
// write
System.out.println(" Writer " + Thread.currentThread().getId() + " stopped writing");
WriterUnlock();
}catch(InterruptedException e){
System.out.println(e);
}
}).start();
}
}
public static void main(String[] args) {
new ReadersWriters();
}
}