-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathOddEvenPrinter.java
76 lines (68 loc) · 2.35 KB
/
OddEvenPrinter.java
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
package org.alxkm.patterns.oddevenprinter;
/**
* The OddEvenPrinter class demonstrates printing odd and even numbers in separate threads.
* It synchronizes the printing process to ensure that odd and even numbers are printed in alternating order.
*/
public class OddEvenPrinter {
private final Object lock = new Object();
private boolean isOddTurn = true;
private final int limit = 10;
private final StringBuilder printedOutput = new StringBuilder();
/**
* Starts the threads for printing odd and even numbers.
*/
public void startPrinting() {
Thread oddThread = new Thread(this::printOddNumbers);
Thread evenThread = new Thread(this::printEvenNumbers);
oddThread.setName("OddThread");
evenThread.setName("EvenThread");
evenThread.start();
oddThread.start();
try {
oddThread.join();
evenThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void printOddNumbers() {
synchronized (lock) {
for (int i = 1; i <= limit; i += 2) {
try {
while (!isOddTurn) {
lock.wait();
}
printedOutput.append(Thread.currentThread().getName()).append(": ").append(i).append("\n");
isOddTurn = false;
lock.notify();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
private void printEvenNumbers() {
synchronized (lock) {
for (int i = 2; i <= limit; i += 2) {
try {
while (isOddTurn) {
lock.wait();
}
printedOutput.append(Thread.currentThread().getName()).append(": ").append(i).append("\n");
isOddTurn = true;
lock.notify();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
/**
* Retrieves the printed output containing the odd and even numbers.
*
* @return the printed output
*/
public String getPrintedOutput() {
return printedOutput.toString();
}
}