-
Notifications
You must be signed in to change notification settings - Fork 0
/
RandomNumberGeneratorOddEvenThread.java
112 lines (96 loc) · 2.46 KB
/
RandomNumberGeneratorOddEvenThread.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
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
104
105
106
107
108
109
110
111
112
import java.util.Random;
import java.util.Scanner;
public class RandomNumberGeneratorOddEvenThread {
public static void main(String [] args) {
System.out.println("Enter the limit");
Scanner sc=new Scanner(System.in);
int limit=sc.nextInt();
numberManager object=new numberManager();
NumberGenerator number=new NumberGenerator(object,limit);
number.start();
EvenPrint number2=new EvenPrint(object);
number2.start();
OddPrint number3=new OddPrint(object);
number3.start();
sc.close();
}
}
class numberManager{
private int generatedNumber;
private boolean numberGeneration=false;
synchronized public void generateNumber() {
generatedNumber= new Random().nextInt(99)+1; //Random number generates from 1
System.out.println("The generated random number is: "+generatedNumber);
numberGeneration=true;
notifyAll();
}
public synchronized void printEvenNumbers() throws InterruptedException {
while(!numberGeneration || generatedNumber!=0) {
wait();
}
for(int i=2;i<generatedNumber;i+=2) {
System.out.print(i+" ");
numberGeneration=false;
}
System.out.println();
}
public synchronized void printOddNumbers() throws InterruptedException {
while(!numberGeneration || generatedNumber==0) {
wait();
}
for(int i=1;i<generatedNumber;i+=2) {
System.out.print(i+" ");
numberGeneration=false;
}
System.out.println();
}
}
class NumberGenerator extends Thread{
numberManager number=new numberManager();
int limit,count=1;
public NumberGenerator(numberManager number,int limit) {
this.number=number;
this.limit=limit;
}
public void run() {
while(true && count<=limit) {
number.generateNumber();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
}
}
class EvenPrint extends Thread{
numberManager number=new numberManager();
public EvenPrint(numberManager number) {
this.number=number;
}
public void run() {
while(true) {
try {
number.printEvenNumbers();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class OddPrint extends Thread{
numberManager number=new numberManager();
public OddPrint(numberManager number) {
this.number=number;
}
public void run() {
while(true) {
try {
number.printOddNumbers();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}