线程分组使得我们可以将一组线程视作单个单元,并提供了方法可以操作她们。 例如,您有某些线程在做同样的任务,您希望控制她们,不管有多少个线程还在运行、每个线程的状态如何,一个调用将打断所有线程。
Java 提供了 ThreadGroup 类。一个 ThreadGroup 对象能由 Thread 对象和其他的 ThreadGroup 对象组成,形成线程的树状结构。
本节的示例代码在 com.elanzone.books.noteeg.chpt1.sect11 package中
搜索结果类 (Result)
private String name;
线程类 (SearchTask)
private Result result; public SearchTask(Result result) { this.result = result; }
String name=Thread.currentThread().getName(); System.out.printf("Thread %s: Start\n",name); try { doTask(); result.setName(name); } catch (InterruptedException e) { System.out.printf("Thread %s: Interrupted\n",name); return; } System.out.printf("Thread %s: End\n",name);
private void doTask() throws InterruptedException { Random random=new Random((new Date()).getTime()); int value=(int)(random.nextDouble()*100); System.out.printf("Thread %s: sleep %d seconds.\n",Thread.currentThread().getName(),value); TimeUnit.SECONDS.sleep(value); }
控制类 (Main)
ThreadGroup threadGroup = new ThreadGroup("Searcher");
Result result = new Result(); SearchTask searchTask = new SearchTask(result);
Thread thread = new Thread(threadGroup, searchTask);
threadGroup.list();
Thread[] threads = new Thread[threadGroup.activeCount()]; threadGroup.enumerate(threads);
threadGroup.interrupt();