forked from Java2ArkTS/Java2ArkTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadWrite.java
More file actions
107 lines (104 loc) · 2.76 KB
/
Copy pathReadWrite.java
File metadata and controls
107 lines (104 loc) · 2.76 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
public class ReadWrite {
public static void main(String[] args) {
Semaphores semaphores = new Semaphores();
Thread thread0 = new Thread(new Reader(semaphores, 0));
Thread thread1 = new Thread(new Reader(semaphores, 1));
Thread thread2 = new Thread(new Reader(semaphores, 2));
Thread thread3 = new Thread(new Writer(semaphores, 3));
Thread thread4 = new Thread(new Writer(semaphores, 4));
thread0.start();
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
class Semaphores {
public int count;
public boolean rw;
public boolean w;
public boolean mutex;
public Semaphores() {
this.count = 0;
this.rw = true;
this.w = true;
this.mutex = true;
}
public synchronized boolean Pw() {
if (w) {
w = false;
return true;
} else {
return false;
}
}
public synchronized boolean Pmutex() {
if (mutex) {
mutex = false;
return true;
} else {
return false;
}
}
public synchronized boolean Prw() {
if (rw) {
rw = false;
return true;
} else {
return false;
}
}
public synchronized void Vmutex() {
mutex = true;
}
public synchronized void Vw() {
w = true;
}
public synchronized void Vrw() {
rw = true;
}
}
class Reader implements Runnable {
public Semaphores semaphores;
public int rank;
public Reader(Semaphores semaphores, int rank) {
this.semaphores = semaphores;
this.rank = rank;
}
public void run() {
while (true) {
while (!semaphores.Pw()) {}
while (!semaphores.Pmutex()) {}
if (semaphores.count == 0) {
while (!semaphores.Prw()) {}
}
semaphores.count++;
semaphores.Vmutex();
semaphores.Vw();
System.out.println("Thread " + rank + " is reading.");
while (!semaphores.Pmutex()) {}
semaphores.count--;
if (semaphores.count == 0) {
semaphores.Vrw();
}
semaphores.Vmutex();
}
}
}
class Writer implements Runnable {
public Semaphores semaphores;
public int rank;
public Writer(Semaphores semaphores, int rank) {
this.semaphores = semaphores;
this.rank = rank;
}
public void run() {
while (true) {
while (!semaphores.Pw()) {}
while (!semaphores.Prw()) {}
System.out.println("Thread " + rank + " is writing.");
semaphores.Vrw();
semaphores.Vw();
}
}
}