-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOddEven.java
More file actions
65 lines (57 loc) · 1.72 KB
/
OddEven.java
File metadata and controls
65 lines (57 loc) · 1.72 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
package PracticeQuestions;
public class OddEven {
public static void main(String[] args) {
SharedPrinter printer = new SharedPrinter(1, 30); // print 1 to 30
Thread oddThread = new Thread(() -> {
try {
printer.printOdd();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread evenThread = new Thread(() -> {
try {
printer.printEven();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
oddThread.start();
evenThread.start();
}
}
class SharedPrinter {
private int number;
private final int max;
private final Object lock = new Object();
public SharedPrinter(int start, int max) {
this.number = start;
this.max = max;
}
public void printOdd() throws InterruptedException {
while (number <= max) {
synchronized (lock) {
if (number % 2 == 0) {
lock.wait();
} else {
System.out.println("Odd: " + number + " by " + Thread.currentThread().getName());
number++;
lock.notify();
}
}
}
}
public void printEven() throws InterruptedException {
while (number <= max) {
synchronized (lock) {
if (number % 2 != 0) {
lock.wait();
} else {
System.out.println("Even: " + number + " by " + Thread.currentThread().getName());
number++;
lock.notify();
}
}
}
}
}