当前位置:嗨网首页>书籍在线阅读

46-案例实现

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

案例实现

根据以下步骤完成本案例。

1.创建一个名为 MyThreadGroup 的类,并继承 ThreadGroup 类进行扩展。 ThreadGroup 类没有无参构造器,因此必须声明一个拥有一个参数的构造器。为了处理线程组抛出的异常,还需要重写 uncaughtException() 方法:

public class MyThreadGroup extends ThreadGroup {
  public MyThreadGroup(String name) {
    super(name);
  }

2.重写 uncaughtException() 方法。 ThreadGroup 类中的任意一个线程抛出异常,都将调用该方法。在本案例中,该方法将在控制台上输出异常和线程的信息。同时需要注意,该方法会中断线程组中的其余线程:

@Override
public void uncaughtException(Thread t, Throwable e) {
  System.out.printf("The thread %s has thrown an Exception\n",
                    t.getId());
  e.printStackTrace(System.out);
  System.out.printf("Terminating the rest of the Threads\n");
  interrupt();
}

3.创建一个名为 Task 的类,并实现 Runnable 接口:

public class Task implements Runnable {

4.实现 run() 方法。在本案例中,我们将构造一个 AritmethicException 异常。不断用1000除以随机生成的整数,直到生成的随机数为零,这时会抛出异常:

@Override
public void run() {
  int result;
  Random random=new Random(Thread.currentThread().getId());
  while (true) {
    result=1000/((int)(random.nextDouble()*1000000000));
    if (Thread.currentThread().isInterrupted()) {
      System.out.printf("%d : Interrupted\n",
                        Thread.currentThread().getId());
      return;
    }
  }
}

5.实现应用程序入口,创建包含 main() 方法的 Main 类:

public class Main {
  public static void main(String[] args) {

6.计算将要启动的线程数。使用 Runtime 类的 availableProcessors() 方法[使用 Runtime 类的静态方法 getRuntime() 得到当前应用的 Runtime 对象],可以得到JVM中可用的处理器数,它通常与运行该应用的计算机内核数一致:

int numberOfThreads = 2 * Runtime.getRuntime()
                              .availableProcessors();

7.创建 MyThreadGroup 类的对象:

MyThreadGroup threadGroup=new MyThreadGroup("MyThreadGroup");

8.创建 Task 类的对象:

Task task=new Task();

9.创建之前计算得出的数量的 Thread 对象,执行 task 并启动:

for (int i = 0; i < numberOfThreads; i++) {
  Thread t = new Thread(threadGroup, task);
  t.start();
}

10.向控制台输出 ThreadGroup 的信息:

System.out.printf("Number of Threads: %d\n",
                  threadGroup.activeCount());
System.out.printf("Information about the Thread Group\n");
threadGroup.list();

11.输出线程组中各线程状态:

  Thread[] threads = new Thread[threadGroup.activeCount()];
  threadGroup.enumerate(threads);
  for (int i = 0; i < threadGroup.activeCount(); i++) {
    System.out.printf("Thread %s: %s\n", threads[i].getName(),
                      threads[i].getState());
    }
  }
}

12.运行案例并查看结果。