-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.java
More file actions
57 lines (53 loc) · 2.3 KB
/
Copy pathApp.java
File metadata and controls
57 lines (53 loc) · 2.3 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
/* This program simulates the Reader-Writer Problem.
* It prompts the user for the number of readers and writers, and then initiates threads for each reader and writer.
* The readers and writers access the shared resource using synchronization mechanisms. The program demonstrates concurrent access to shared
* data and helps illustrate the challenges of coordinating multiple readers and writers effectively.
**/
public class App {
public static void main(String[] args) {
System.out.println("\n#################################################################################################");
System.out.println(" ** Reader-Writer Problem Simulation ** ");
int readerCount = getInput(" ---> Enter the number of readers: ");
int writerCount = getInput(" ---> Enter the number of writers: ");
simulateReadersWriters(readerCount, writerCount);
}
public static void simulateReadersWriters(int readerCount, int writerCount) {
Thread[] readers = new Thread[readerCount];
Thread[] writers = new Thread[writerCount];
for (int i = 0; i < readerCount; i++) {
final int readerId = i + 1;
readers[i] = new Thread(new Runnable() {
@Override
public void run() {
ReaderWriter readerWriter = new ReaderWriter();
readerWriter.startReading(readerId);
}
});
readers[i].start();
}
for (int i = 0; i < writerCount; i++) {
final int writerId = i + 1;
writers[i] = new Thread(new Runnable() {
@Override
public void run() {
ReaderWriter readerWriter = new ReaderWriter();
readerWriter.startWriting(writerId);
}
});
}
try {
for (Thread reader : readers) {
reader.join();
}
for (Thread writer : writers) {
writer.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static int getInput(String prompt) {
System.out.print(prompt);
return Integer.parseInt(System.console().readLine());
}
}