-
Notifications
You must be signed in to change notification settings - Fork 243
/
threads.java
57 lines (54 loc) · 1.47 KB
/
threads.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
import java.util.Random;
class Square extends Thread{
int x;
Square(int n){
x = n;
}
public void run(){
int sqr = x * x;
System.out.println("Square of " + x + " = " + sqr );
}
}
class Cube extends Thread{
int x;
Cube(int n){
x = n;
}
public void run(){
int cub = x * x * x;
System.out.println("Cube of " + x + " = " + cub );
}
}
class Number extends Thread{
public void run(){
Random random = new Random();
for(int i =0; i<10; i++){
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
if(randomInteger % 2 == 0){
Square s = new Square(randomInteger);
s.start();
}
else{
Cube c = new Cube(randomInteger);
c.start();
}
try {
Thread.sleep(1000);
// This thread generates random number 10 times
// between 1 to 100 for every 1 second. The generated
// random number is then passed as argument to
// Square and Cube threads.
// Output varies each time a program is executed.
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
public class threads {
public static void main(String args[]) {
Number n = new Number();
n.start();
}
}