-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyClass.java
67 lines (63 loc) · 2.06 KB
/
MyClass.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class MyClass{
public static void main(String args[]){
MyThreadClass t1=new MyThreadClass("odd", 1000);
MyThreadClass t2=new MyThreadClass("Even", 1000);
t1.start();
t2.start();
}
public static class MyThreadClass extends Thread {
String type;
int max;
MyThreadClass(String type, int max) {
this.max = max;
this.type = type;
}
public void run() {
if(this.type.equals("odd")) {
Thread.currentThread().setName("ODD Thread");
OddEven odd = new OddEven();
odd.printOdd(this.max);
} else {
Thread.currentThread().setName("Even Thread");
OddEven even = new OddEven();
even.printEven(this.max);
}
}
}
public static class OddEven {
static boolean isOddPrinted = false;
static Object obj = new Object();
public void printOdd (int max) {
int i = 1;
while(i < max) {
synchronized(obj) {
if(isOddPrinted) {
try {
obj.wait();
} catch(Exception e) {e.printStackTrace();}
}
System.out.println("odd " + i);
i = i+2;
isOddPrinted = true;
obj.notify();
}
}
}
public void printEven(int max) {
int i = 2;
while(i < max) {
synchronized(obj) {
if(!isOddPrinted) {
try {
obj.wait();
} catch(Exception e) {e.printStackTrace();}
}
System.out.println("Even " + i);
i = i+2;
isOddPrinted = false;
obj.notify();
}
}
}
}
}