forked from Java2ArkTS/Java2ArkTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
85 lines (72 loc) · 2.17 KB
/
Copy pathMain.java
File metadata and controls
85 lines (72 loc) · 2.17 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
class SharedResource {
private int data = 0;
private volatile boolean isWriting = false;
private volatile int readers = 0;
public void readData() throws InterruptedException {
while (isWriting) {
// Spin-wait while a write is in progress
for(int i=0;i<1000;i++); // Introduce a small delay to reduce CPU usage
}
synchronized (this) {
readers++;
}
System.out.println("Reading data: " + data);
synchronized (this) {
readers--;
}
}
public void writeData(int newData) throws InterruptedException {
while (readers > 0 || isWriting) {
// Spin-wait while there are readers or another write is in progress
for(int i=0;i<1000;i++); // Introduce a small delay to reduce CPU usage
}
isWriting = true;
System.out.println("Writing data: " + newData);
data = newData;
isWriting = false;
}
}
class Reader implements Runnable {
private SharedResource resource;
public Reader(SharedResource resource) {
this.resource = resource;
}
@Override
public void run() {
try {
resource.readData();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Writer implements Runnable {
private SharedResource resource;
private int newData;
public Writer(SharedResource resource, int newData) {
this.resource = resource;
this.newData = newData;
}
@Override
public void run() {
try {
resource.writeData(newData);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
// Multiple reader threads
for (int i = 0; i < 5; i++) {
Thread readerThread = new Thread(new Reader(resource));
readerThread.start();
}
// Single writer thread
int newData = 42;
Thread writerThread = new Thread(new Writer(resource, newData));
writerThread.start();
}
}