此例子用来演示 ThreadGroup 的一些作用
/** |
02 |
* Simple demo of ThreadGroup usage. |
03 |
*/ |
04 |
public class ThreadGroupDemo { |
05 |
06 |
class MyThreadGroup extends ThreadGroup { |
07 |
public void uncaughtException(Thread t, Throwable ex) { |
08 |
System.err.println("I caught " + ex); |
09 |
} |
10 |
public MyThreadGroup(String name) { |
11 |
super(name); |
12 |
} |
13 |
} |
14 |
15 |
public static void main(String[] args) { |
16 |
new ThreadGroupDemo().work(); |
17 |
} |
18 |
19 |
protected void work() { |
20 |
ThreadGroup g = new MyThreadGroup("bulk threads"); |
21 |
Runnable r = new Runnable() { |
22 |
public void run() { |
23 |
System.out.println(Thread.currentThread().getName() + " started"); |
24 |
for (int i=0; i<5; i++) { |
25 |
System.out.println(Thread.currentThread().getName() + ": " + i); |
26 |
try { |
27 |
Thread.sleep(1776); |
28 |
} catch (InterruptedException ex) { |
29 |
System.out.println("Huh?"); |
30 |
} |
31 |
} |
32 |
} |
33 |
}; |
34 |
35 |
// Create and start all the Threads |
36 |
for (int i = 0; i< 10; i++) { |
37 |
new Thread(g, r).start(); |
38 |
} |
39 |
40 |
// List them. |
41 |
Thread[] list = new Thread[g.activeCount()]; |
42 |
g.enumerate(list); |
43 |
for (int i=0; i<list.length; i++) { |
44 |
if (list[i] == null) |
45 |
continue; |
46 |
Thread t = list[i]; |
47 |
System.out.println(i + ": " + t); |
48 |
} |
49 |
} |
50 |
} |
51 |
//该片段来自于http://www.codesnippet.cn/detail/05122012834.html |
浙公网安备 33010602011771号