Skip to content

Commit b49dd4f

Browse files
authored
print odd and even using Semaphore
1 parent 8b6e6fd commit b49dd4f

1 file changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package com.baeldung.concurrent.evenandodd;
2+
3+
import java.util.concurrent.Semaphore;
4+
5+
public class SemaphoreDemo {
6+
7+
public static void main(String[] args) {
8+
9+
SharedPrinter sp = new SharedPrinter();
10+
Thread odd = new Thread(new Odd(sp, 10));
11+
odd.setName("Odd");
12+
Thread even = new Thread(new Even(sp, 10));
13+
even.setName("Even");
14+
15+
odd.start();
16+
even.start();
17+
18+
}
19+
20+
}
21+
22+
class SharedPrinter {
23+
24+
Semaphore semEven = new Semaphore(0);
25+
Semaphore semOdd = new Semaphore(1);
26+
27+
public void printEvenNum(int num) {
28+
try {
29+
semEven.acquire();
30+
} catch (InterruptedException e) {
31+
e.printStackTrace();
32+
}
33+
System.out.println(Thread.currentThread()
34+
.getName() + ":"+num);
35+
semOdd.release();
36+
}
37+
38+
public void printOddNum(int num) {
39+
try {
40+
semOdd.acquire();
41+
} catch (InterruptedException e) {
42+
e.printStackTrace();
43+
}
44+
System.out.println(Thread.currentThread()
45+
.getName() + ":"+ num);
46+
semEven.release();
47+
48+
}
49+
}
50+
51+
class Even implements Runnable {
52+
SharedPrinter sp;
53+
int max;
54+
55+
Even(SharedPrinter sp, int max) {
56+
this.sp = sp;
57+
this.max = max;
58+
}
59+
60+
@Override
61+
public void run() {
62+
for (int i = 2; i <= max; i = i + 2) {
63+
sp.printEvenNum(i);
64+
}
65+
}
66+
}
67+
68+
class Odd implements Runnable {
69+
SharedPrinter sp;
70+
int max;
71+
72+
Odd(SharedPrinter sp, int max) {
73+
this.sp = sp;
74+
this.max = max;
75+
}
76+
77+
@Override
78+
public void run() {
79+
for (int i = 1; i <= max; i = i + 2) {
80+
sp.printOddNum(i);
81+
}
82+
}
83+
}

0 commit comments

Comments
 (0)