-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadersWritersDemo.java
More file actions
76 lines (68 loc) · 2.66 KB
/
ReadersWritersDemo.java
File metadata and controls
76 lines (68 loc) · 2.66 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
// 6. READERS-WRITERS PROBLEM - Coordinate multiple readers and exclusive writers
// Problem: Multiple readers can read simultaneously, but writer needs exclusive access
public class ReadersWritersDemo {
static class ReadWriteResource {
private int data = 0;
private int readers = 0;
private int writers = 0;
private int waitingWriters = 0;
// Readers can acquire simultaneously
public synchronized void acquireRead() throws InterruptedException {
while (writers > 0 || waitingWriters > 0) {
wait(); // Wait if writers are active or waiting
}
readers++;
System.out.println("Reader acquired (Active readers: " + readers + ")");
}
public synchronized void releaseRead() {
readers--;
System.out.println("Reader released (Active readers: " + readers + ")");
if (readers == 0) {
notifyAll(); // Notify waiting writers
}
}
// Writers need exclusive access
public synchronized void acquireWrite() throws InterruptedException {
waitingWriters++;
while (readers > 0 || writers > 0) {
wait(); // Wait if any readers or writers are active
}
waitingWriters--;
writers++;
System.out.println("Writer acquired (Writing...)");
}
public synchronized void releaseWrite() {
writers--;
data++;
System.out.println("Writer released (Data updated to: " + data + ")");
notifyAll(); // Notify waiting readers/writers
}
public int readData() {
return data;
}
}
public static void main(String[] args) {
ReadWriteResource resource = new ReadWriteResource();
// Create multiple reader threads
for (int i = 0; i < 3; i++) {
new Thread(() -> {
try {
resource.acquireRead();
System.out.println(" Reader reading data: " + resource.readData());
Thread.sleep(500);
resource.releaseRead();
} catch (InterruptedException e) {}
}).start();
}
// Create writer thread
new Thread(() -> {
try {
Thread.sleep(100);
resource.acquireWrite();
System.out.println(" Writer updating data...");
Thread.sleep(500);
resource.releaseWrite();
} catch (InterruptedException e) {}
}).start();
}
}