-
Notifications
You must be signed in to change notification settings - Fork 0
/
printeo.txt
103 lines (89 loc) · 2.23 KB
/
printeo.txt
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone{
public static void main(String[] args) {
// shared class object
SharedPrinter sp = new SharedPrinter();
// creating two threads
Thread t1 = new Thread(new EvenNumProducer(sp, 10));
Thread t2 = new Thread(new OddNumProducer(sp, 10));
// starting threads
t1.start();
t2.start();
}
}
// Shared class used by both threads
class SharedPrinter{
boolean evenFlag = false;
//Method for printing even numbers
public void printEvenNum(int num){
synchronized (this) {
// While condition as mandated to avoid spurious wakeup
while(!evenFlag){
try {
//asking current thread to give up lock
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(num);
evenFlag = false;
// Wake up thread waiting on this monitor(lock)
notify();
}
}
//Method for printing odd numbers
public void printOddNum(int num){
synchronized (this) {
// While condition as mandated to avoid spurious wakeup
while(evenFlag){
try {
//asking current thread to give up lock
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(num);
evenFlag = true;
// Wake up thread waiting on this monitor(lock)
notify();
}
}
}
// Thread Class generating Even numbers
class EvenNumProducer implements Runnable{
SharedPrinter sp;
int index;
EvenNumProducer(SharedPrinter sp, int index){
this.sp = sp;
this.index = index;
}
@Override
public void run() {
for(int i = 2; i <= index; i = i+2){
sp.printEvenNum(i);
}
}
}
//Thread Class generating Odd numbers
class OddNumProducer implements Runnable{
SharedPrinter sp;
int index;
OddNumProducer(SharedPrinter sp, int index){
this.sp = sp;
this.index = index;
}
@Override
public void run() {
for(int i = 1; i <= index; i = i+2){
sp.printOddNum(i);
}
}
}