-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathEvenOddRunnable.java
More file actions
36 lines (35 loc) · 1.08 KB
/
EvenOddRunnable.java
File metadata and controls
36 lines (35 loc) · 1.08 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
package Thread;
public class EvenOddRunnable implements Runnable{
int MAX;
static int counter = 1;
int rem;
static Object lock = new Object();
// parameterized constructor
EvenOddRunnable(int rem, int MAX)
{
this.rem = rem;
this.MAX = MAX;
}
// override run() method
@Override
public void run() {
// use while loop to recursively execute steps until counter < MAX
while (counter < MAX) {
// synchronized block
synchronized (lock) {
while (counter % 2 != rem) { // wait for numbers other than remainder
// use try-catch block to put lock in waiting state
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " " + counter);
//increment counter
counter++;
lock.notifyAll();
}
}
}
}