-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJoinDemo.java
More file actions
59 lines (48 loc) · 1.36 KB
/
Copy pathJoinDemo.java
File metadata and controls
59 lines (48 loc) · 1.36 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
package threadbook.ch08;
public class JoinDemo extends Object {
public static Thread launch(String name, long napTime) {
final long sleepTime = napTime;
Runnable r = new Runnable() {
public void run() {
try {
print("in run() - entering");
Thread.sleep(sleepTime);
} catch ( InterruptedException x ) {
print("interrupted!");
} finally {
print("in run() - leaving");
}
}
};
Thread t = new Thread(r, name);
t.start();
return t;
}
private static void print(String msg) {
String name = Thread.currentThread().getName();
System.out.println(name + ": " + msg);
}
public static void main(String[] args) {
Thread[] t = new Thread[3];
t[0] = launch("threadA", 2000);
t[1] = launch("threadB", 1000);
t[2] = launch("threadC", 3000);
for ( int i = 0; i < t.length; i++ ) {
try {
String idxStr = "t[" + i + "]";
String name = "[" + t[i].getName() + "]";
print(idxStr + ".isAlive()=" +
t[i].isAlive() + " " + name);
print("about to do: " + idxStr +
".join() " + name);
long start = System.currentTimeMillis();
t[i].join(); // wait for the thread to die
long stop = System.currentTimeMillis();
print(idxStr + ".join() - took " +
( stop - start ) + " ms " + name);
} catch ( InterruptedException x ) {
print("interrupted waiting on #" + i);
}
}
}
}