-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOddEvenRunnable.java
45 lines (36 loc) · 1020 Bytes
/
OddEvenRunnable.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
package ProblemWithSolutions;
public class OddEvenRunnable implements Runnable {
public int PRINT_NUMBERS_UPTO = 10;
static int number = 1;
int remainder;
static Object lock = new Object();
OddEvenRunnable(int remainder) {
this.remainder = remainder;
}
@Override
public void run() {
while (number < PRINT_NUMBERS_UPTO) {
synchronized (lock) {
while (number % 2 != remainder) { // wait for numbers other than
// remainder
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " " + number);
number++;
lock.notifyAll();
}
}
}
public static void main(String[] args) {
OddEvenRunnable oddRunnable = new OddEvenRunnable(1);
OddEvenRunnable evenRunnable = new OddEvenRunnable(0);
Thread t1 = new Thread(oddRunnable, "Odd");
Thread t2 = new Thread(evenRunnable, "Even");
t1.start();
t2.start();
}
}