-
Notifications
You must be signed in to change notification settings - Fork 0
/
OddEvenTwoThread.java
65 lines (63 loc) · 1.17 KB
/
OddEvenTwoThread.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
class Print
{
boolean isOdd = false;
synchronized void printEven(int number)
{
while(isOdd == false)
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Even" +number);
isOdd = false;
notifyAll();
}
synchronized void printOdd(int number)
{
while(isOdd == true)
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Odd " +number);
isOdd = true;
notifyAll();
}
}
class TaskEvenOdd implements Runnable {
boolean isEven;
Print mPrint;
public TaskEvenOdd(boolean isEven, Print p) {
this.isEven = isEven;
mPrint = p;
}
@Override
public void run() {
int i = isEven ? 2 : 1;
for(; i <= 10; i+=2)
{
if(isEven)
mPrint.printEven(i);
else
mPrint.printOdd(i);
}
}
}
public class OddEvenTwoThread {
public static void main(String[] args) {
Print p = new Print();
Thread t1 = new Thread(new TaskEvenOdd(true, p));
Thread t2 = new Thread(new TaskEvenOdd(false, p));
t1.start();
t2.start();
System.out.println("Main thread");
}
}