Skip to content

Commit 7214019

Browse files
authored
Create EvenOddPrinter.java
1 parent cd9f84f commit 7214019

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

exercise/EvenOddPrinter.java

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
public class EvenOddPrinter {
2+
private static volatile boolean flag = true; // Use volatile to ensure visibility across threads
3+
4+
public static void main(String[] args) {
5+
Runnable odd = () -> {
6+
for (int i = 1; i <= 10; i += 2) {
7+
synchronized (EvenOddPrinter.class) {
8+
while (!flag) {
9+
try {
10+
EvenOddPrinter.class.wait();
11+
} catch (InterruptedException e) {
12+
e.printStackTrace();
13+
}
14+
}
15+
System.out.println(Thread.currentThread().getName() + " " + i);
16+
flag = false;
17+
EvenOddPrinter.class.notify(); // Notify waiting thread (even thread)
18+
}
19+
}
20+
};
21+
22+
Runnable even = () -> {
23+
for (int i = 2; i <= 10; i += 2) {
24+
synchronized (EvenOddPrinter.class) {
25+
while (flag) {
26+
try {
27+
EvenOddPrinter.class.wait();
28+
} catch (InterruptedException e) {
29+
e.printStackTrace();
30+
}
31+
}
32+
System.out.println(Thread.currentThread().getName() + " " + i);
33+
flag = true;
34+
EvenOddPrinter.class.notify(); // Notify waiting thread (odd thread)
35+
}
36+
}
37+
};
38+
39+
Thread t1 = new Thread(odd, "OddThread");
40+
Thread t2 = new Thread(even, "EvenThread");
41+
42+
t1.start();
43+
t2.start();
44+
}
45+
}

0 commit comments

Comments
 (0)