君子博学而日参省乎己 则知明而行无过矣

博客园 首页 新随笔 联系 订阅 管理

此例子用来演示 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
posted on 2013-07-23 03:33  刺猬的温驯  阅读(129)  评论(0)    收藏  举报