-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path03.b.MultiThreading.java
More file actions
71 lines (61 loc) · 1.77 KB
/
03.b.MultiThreading.java
File metadata and controls
71 lines (61 loc) · 1.77 KB
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
/*
3.b. Write a Java program that implements a multi-thread application that has three threads.
First thread generates a random integer for every 1 second; second thread computes the
square of the number and prints; third thread will print the value of cube of the number.
*/
import java.util.Random;
class Generator extends Thread {
static int number;
@Override
public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
number = random.nextInt(10) + 1;
System.out.println("\nRandom Number: " + number);
Main.square.interrupt();
Main.cube.interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Square extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(99999);
} catch (InterruptedException e) {
System.out.println("Square: " + (Generator.number * Generator.number));
}
}
}
}
class Cube extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(99999);
} catch (InterruptedException e) {
System.out.println("Cube: " + (Generator.number * Generator.number * Generator.number));
}
}
}
}
class Main {
static Thread generator;
static Thread square;
static Thread cube;
public static void main(String[] args) {
generator = new Generator();
square = new Square();
cube = new Cube();
square.start();
cube.start();
generator.start();
}
}