-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMultiThreadDemo.java
More file actions
55 lines (47 loc) · 1.2 KB
/
MultiThreadDemo.java
File metadata and controls
55 lines (47 loc) · 1.2 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
/**
*
*/
import java.util.Random;
/**
* Shows an example of multi-threading.
*
* @author Massimiliano "Maxi" Zattera
*
*/
public class MultiThreadDemo extends Thread {
private final static Random rnd = new Random(666);
private final String name;
// must do this as strings are not garbage collected and wil cause out of memory
private final String sleepMsg;
private final String wakeUpMsg;
private MultiThreadDemo(String name) {
this.name = name;
sleepMsg = name + " is going to sleep...";
wakeUpMsg = name + " wakes up and says hello! :-)";
System.out.println(name + " created.");
}
@Override
public void run() {
while (true) {
int sleepTime = rnd.nextInt(3) + 1;
System.out.println(sleepMsg);
try {
Thread.sleep(sleepTime*1000);
} catch (InterruptedException e) {
break;
}
System.out.println(wakeUpMsg);
}
}
public static void main(String[] args) throws Exception {
String[] names = {"Inky", "Blinky", "Pinky", "Clyde"};
MultiThreadDemo[] t = new MultiThreadDemo[names.length];
for (int i = 0; i < names.length; ++i) {
t[i] = new MultiThreadDemo(names[i]);
}
for (int i = 0; i < t.length; ++i) {
t[i].start();
}
while (true) {}
}
}