-
Notifications
You must be signed in to change notification settings - Fork 0
/
RandomNumberCubeSquare.java
113 lines (94 loc) · 2.39 KB
/
RandomNumberCubeSquare.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
113
import java.util.Random;
import java.util.Scanner;
public class RandomNumberCubeSquare {
public static void main(String[] args) {
System.out.println("Enter the limit");
Scanner sc=new Scanner(System.in);
int limit=sc.nextInt();
NumberManager number=new NumberManager();
NumberGenerator generatedNumber=new NumberGenerator(number,limit);
generatedNumber.start();
SquareThread even=new SquareThread(number);
even.start();
OddThread odd=new OddThread(number);
odd.start();
sc.close();
}
}
class NumberManager{
private int numberGenerated;
private boolean generationStatus=false;
synchronized public void RandomNumberGeneration() {
numberGenerated=new Random().nextInt(100)+1; //Upto 99 from 1
System.out.println("The number generated is : "+numberGenerated);
generationStatus=true;
notifyAll();
}
synchronized public void EvenNumberSquare() throws InterruptedException {
if(!generationStatus || numberGenerated%2!=0) {
wait();
}
else {
System.out.println("The square of the "+numberGenerated+ " : "+numberGenerated*numberGenerated);
generationStatus=false;
}
}
synchronized public void OddNumberCube() throws InterruptedException {
if(!generationStatus || numberGenerated%2==0) {
wait();
}
else {
System.out.println("The cube of the "+numberGenerated+ " : "+numberGenerated*numberGenerated*numberGenerated);
generationStatus=false;
}
}
}
class SquareThread extends Thread{
private NumberManager square=new NumberManager();
SquareThread(NumberManager square) {
this.square=square;
}
public void run() {
while(true) {
try {
square.EvenNumberSquare();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class OddThread extends Thread{
private NumberManager cube=new NumberManager();
OddThread(NumberManager cube) {
this.cube=cube;
}
public void run() {
while(true) {
try {
cube.OddNumberCube();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class NumberGenerator extends Thread{
NumberManager number=new NumberManager();
int count=0,limit;
public NumberGenerator(NumberManager number,int limit) {
this.limit=limit;
this.number=number;
}
public void run() {
while(true && count<limit) {
number.RandomNumberGeneration();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
}
}