Что такое threadgroup и зачем он нужен
Русские Блоги
Группа потоков Java ThreadGroup
Аннотация: ThreadGroup ThreadGroup представляет собой набор потоков, и если поток принадлежит группе потоков, он не может быть заменен группой потоков, к которой он принадлежит. Так зачем использовать группу потоков? Я лично считаю, что он имеет следующие преимущества: удобное унифицированное управление, можно копировать группы потоков, быстро находить поток и унифицировать настройки исключений. ThreadGroup на самом деле не принадлежит содержимому параллельного пакета Java, это содержимое java.lang. Однако овладение его пониманием очень помогает в практическом применении.
Во-первых, основной метод
1. Получить имя текущей группы потоков
Основной метод вызывается и вывод: основной
2. Поместите темы в группу потоков.
Среди них конструктор, связанный с ThreadGroup в Thread:
Все они в конечном итоге вызывают одну и ту же функцию:
3. Скопируйте группу потоков:
ActiveCount здесь, очевидно, поток, который получает активность, обратите внимание. По умолчанию он также копируется с дочерними группами потоков.
4. Необработанная обработка исключений
В ThreadGroup есть метод uncaughtException (). Когда в потоке в группе потоков возникает исключение Unchecked, среда выполнения вызывает этот метод для связанной обработки. При необходимости вы можете переопределить этот метод
Примеры применения
1. Пример приложения
2, унифицированные примеры обработки исключений
В-третьих, интерпретация исходного кода
Сначала посмотрите на переменные, которые он содержит
Настройки необработанных исключений:
Если родительская группа потоков существует, вызывается ее метод uncaughtException.
Если родительская группа потоков не существует, но указан обработчик по умолчанию (как обработчик по умолчанию для приложения в следующем разделе), вызывается обработчик по умолчанию
Если обработчик по умолчанию не установлен, запишите журнал ошибок. Но если исключение является экземпляром ThreadDeath, игнорируйте его
Класс Java.lang.ThreadGroup в Java
ThreadGroup создает группу потоков. Он предлагает удобный способ управления группами потоков как единым целым. Это особенно ценно в ситуации, когда вы хотите приостановить и возобновить ряд связанных тем.
Конструкторы:
методы
// Java-код, иллюстрирующий метод activeCount ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 1000 ; i++)
catch (InterruptedException ex)
System.out.println( «Exception encounterted» );
public class ThreadGroupDemo
public static void main(String arg[])
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «parent thread group» );
System.out.println( «Starting one» );
System.out.println( «Starting two» );
// проверка количества активных потоков
System.out.println( «number of active thread: «
// Java-код, иллюстрирующий метод activeGroupCount ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 1000 ; i++)
catch (InterruptedException ex)
System.out.println( «Exception encounterted» );
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «gfg» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child» );
System.out.println( «Starting one» );
System.out.println( «Starting two» );
// проверка количества активных потоков
System.out.println( «number of active thread group: «
// Java-код, иллюстрирующий метод checkAccess ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 1000 ; i++)
catch (InterruptedException ex)
System.out.println( «Exception encounterted» );
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting one» );
System.out.println( «Starting two» );
System.out.println(gfg.getName() + » has access» );
System.out.println(gfg_child.getName() + » has access» );
// Java-код, иллюстрирующий метод destroy ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Exception encounterted» );
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting one» );
System.out.println( «Starting two» );
// блокировать, пока не закончится другой поток
// уничтожаем дочерний поток
// уничтожаем родительский поток
// Java-код, иллюстрирующий метод enumerate ().
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex) <
System.out.println( «Exception encounterted» );
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting one» );
System.out.println( «Starting two» );
// возвращает количество потоков, помещенных в массив
Thread[] group = new Thread[gfg.activeCount()];
int count = gfg.enumerate(group);
System.out.println( «Thread » + group[i].getName() + » found» );
// Java-код, иллюстрирующий перечисление (группа Thread [], логический рекурс)
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Exception encounterted» );
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting one» );
System.out.println( «Starting two» );
// возвращает количество потоков, помещенных в массив
Thread[] group = new Thread[gfg.activeCount()];
int count = gfg.enumerate(group, true );
System.out.println( «Thread » + group[i].getName() + » found» );
// Java-код, иллюстрирующий метод enumerate (ThreadGroup [] group)
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Exception encounterted» );
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting one» );
System.out.println( «Starting two» );
// возвращает количество потоков, помещенных в массив
ThreadGroup[] group = new ThreadGroup[gfg.activeCount()];
int count = gfg.enumerate(group);
System.out.println( «ThreadGroup » + group[i].getName() +
// код Java, иллюстрирующий перечисление (группа ThreadGroup [], логическое все)
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Exception encounterted» );
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting one» );
System.out.println( «Starting two» );
// возвращает количество потоков, помещенных в массив
ThreadGroup[] group = new ThreadGroup[gfg.activeCount()];
int count = gfg.enumerate(group, true );
System.out.println( «ThreadGroup » + group[i].getName() +
// Java-код, иллюстрирующий метод getMaxPriority ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Exception encounterted» );
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
// проверка максимального приоритета родительского потока
System.out.println( «Maximum priority of ParentThreadGroup = «
System.out.println( «Starting one» );
System.out.println( «Starting two» );
// Java-код, иллюстрирующий метод getName ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Exception encounterted» );
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting » + t1.getName());
System.out.println( «Starting » + t2.getName());
// Java-код, иллюстрирующий метод getParent ()
class NewThread extends Thread <
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++) <
catch (InterruptedException ex) <
System.out.println( «Exception encounterted» );
> public class ThreadGroupDemo <
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting » + t1.getName());
System.out.println( «Starting » + t2.getName());
// печатает родительскую ThreadGroup
// как родительских, так и дочерних потоков
System.out.println( «ParentThreadGroup for » + gfg.getName() +
System.out.println( «ParentThreadGroup for » + gfg_child.getName()
// Java-код, иллюстрирующий метод interrupt ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Thread » + Thread.currentThread().getName()
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting » + t1.getName());
System.out.println( «Starting » + t2.getName());
// прерывание группы потоков
// Java-код, иллюстрирующий метод isDaemon ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Thread » + Thread.currentThread().getName()
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting » + t1.getName());
System.out.println( «Starting » + t2.getName());
if (gfg.isDaemon() == true )
System.out.println( «Group is Daemon group» );
System.out.println( «Group is not Daemon group» );
// Java-код, иллюстрирующий метод isDestroyed ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Thread » + Thread.currentThread().getName()
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting » + t1.getName());
System.out.println( «Starting » + t2.getName());
if (gfg.isDestroyed() == true )
System.out.println( «Group is destroyed» );
System.out.println( «Group is not destroyed» );
// Java-код, иллюстрирующий метод list ().
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Thread » + Thread.currentThread().getName()
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting » + t1.getName());
System.out.println( «Starting » + t2.getName());
// выводим содержимое родительской ThreadGroup
System.out.println( «\nListing parentThreadGroup: » + gfg.getName()
// печатает информацию об этой группе потоков
// к стандартному выводу
// Java-код, иллюстрирующий метод parentOf ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Thread » + Thread.currentThread().getName()
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting » + t1.getName());
System.out.println( «Starting » + t2.getName());
// проверка, кто является родительским потоком
System.out.println(gfg.getName() + » is parent of » +
// Java-код, иллюстрирующий метод setDaemon ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Thread » + Thread.currentThread().getName()
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
// статус демона установлен в true
// статус демона установлен в true
System.out.println( «Starting » + t1.getName());
System.out.println( «Starting » + t2.getName());
if (gfg.isDaemon() && gfg_child.isDaemon())
System.out.println( «Parent Thread group and «
+ «child thread group»
// Java-код, иллюстрирующий метод setMaxPriority ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Thread » + Thread.currentThread().getName()
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
System.out.println( «Starting » + t1.getName());
System.out.println( «Starting » + t2.getName());
// Java-код, иллюстрирующий метод toString ()
class NewThread extends Thread
NewThread(String threadname, ThreadGroup tgob)
super (tgob, threadname);
for ( int i = 0 ; i 10 ; i++)
catch (InterruptedException ex)
System.out.println( «Thread » + Thread.currentThread().getName()
public class ThreadGroupDemo
public static void main(String arg[]) throws InterruptedException,
// создаем группу потоков
ThreadGroup gfg = new ThreadGroup( «Parent thread» );
ThreadGroup gfg_child = new ThreadGroup(gfg, «child thread» );
// статус демона установлен в true
// статус демона установлен в true
System.out.println( «Starting » + t1.getName());
System.out.println( «Starting » + t2.getName());
// строковый эквивалент родительской группы
System.out.println( «String equivalent: » + gfg.toString());
Пожалуйста, пишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по обсуждаемой выше теме.
Что такое threadgroup и зачем он нужен
A thread is allowed to access information about its own thread group, but not to access information about its thread group’s parent thread group or any other thread groups.
Constructor Summary
Method Summary
Methods inherited from class java.lang.Object
Constructor Detail
ThreadGroup
The checkAccess method of the parent thread group is called with no arguments; this may result in a security exception.
ThreadGroup
The checkAccess method of the parent thread group is called with no arguments; this may result in a security exception.
Method Detail
getName
getParent
getMaxPriority
isDaemon
isDestroyed
setDaemon
First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception.
A daemon thread group is automatically destroyed when its last thread is stopped or its last thread group is destroyed.
setMaxPriority
First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception.
parentOf
checkAccess
activeCount
The value returned is only an estimate because the number of threads may change dynamically while this method traverses internal data structures, and might be affected by the presence of certain system threads. This method is intended primarily for debugging and monitoring purposes.
enumerate
An invocation of this method behaves in exactly the same way as the invocation
enumerate
Due to the inherent race condition in this method, it is recommended that the method only be used for debugging and monitoring purposes.
activeGroupCount
The value returned is only an estimate because the number of thread groups may change dynamically while this method traverses internal data structures. This method is intended primarily for debugging and monitoring purposes.
enumerate
An invocation of this method behaves in exactly the same way as the invocation
enumerate
Due to the inherent race condition in this method, it is recommended that the method only be used for debugging and monitoring purposes.
First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception.
This method then calls the stop method on all the threads in this thread group and in all of its subgroups.
interrupt
First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception.
This method then calls the interrupt method on all the threads in this thread group and in all of its subgroups.
suspend
First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception.
This method then calls the suspend method on all the threads in this thread group and in all of its subgroups.
resume
First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception.
This method then calls the resume method on all the threads in this thread group and in all of its sub groups.
destroy
First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception.
uncaughtException
Applications can override this method in subclasses of ThreadGroup to provide alternative handling of uncaught exceptions.
Уровень 28. Ответы на вопросы к собеседованию по теме уровня
Ответ на этот вопрос есть в лекциях JavaRush.
Для оптимизации параллельной работы нитей в Java имеется возможность устанавливать приоритеты нитей. Нити с большим приоритетом имеют преимущество в получении времени процессора перед нитями с более низким приоритетом.
Работа с приоритетами обеспечивается следующими методами класса Thread :
public final void setPriority(int newPriority)
Устанавливает приоритет нити.
public final int getPriority()
Позволяет узнать приоритет нити.
MIN_PRIORITY = 1.
NORM_PRIORITY =5.
MAX_PRIORITY = 10.
Можно ли остановить нить, снизив ее приоритет до 0?
Ответ в статье: «Топ 50 вопросов на собеседовании. Тема: Многопоточность (Multithreading)»
Конкретно по вопросу: Нигде не видел, чтобы кто-то приоритет выставлял в 0.
Если кто знает об этом что-нибудь, то напишите в комментариях.
ThreadGroup представляет собой набор нитей, которые так же могут содержать в себе другие группы потоков. Группа нитей образует дерево, в котором каждая другая группа нитей имеет родителя (кроме исходной). Поток имеет право доступа к данным из своей группы нитей, но не имеет такого доступа к другим группам или к родительской группе потоков.
Нигде не нашел)) Подскажите где это есть))
На это есть выдержка из статьи на википедии:
In computer programming, the thread pool pattern (also replicated workers or worker-crew model) is where a number of threads are created to perform a number of tasks, which are usually organized in a queue. The results from the tasks being executed might also be placed in a queue, or the tasks might return no result (for example, if the task is for animation). Typically, there are many more tasks than threads. As soon as a thread completes its task, it will request the next task from the queue until all tasks have been completed. The thread can then terminate, or sleep until there are new tasks available.
The number of threads used is a parameter that can be tuned to provide the best performance. Additionally, the number of threads can be dynamic based on the number of waiting tasks. For example, a web server can add threads if numerous web page requests come in and can remove threads when those requests taper down. The cost of having a larger thread pool is increased resource usage. The algorithm used to determine when to create or destroy threads will have an impact on the overall performance:
В компьютерном программировании есть модель пула потоков, где определенное число потоков создается для выполнения целого ряда задач, которые обычно организуются в очереди. Результаты от выполненных задач также могут быть помещены в очередь, либо задачи могут не возвращать никакого результата (например, если задача для анимации).
public class ThreadPoolExecutor extends AbstractExecutorService
ExecutorService это выполняет каждую представленную задачу, используя один возможно из нескольких объединенных в пул потоков, обычно сконфигурированное использование Executors методы фабрики.
Пулы потоков рассматривают две различных проблемы: они обычно обеспечивают улучшенную производительность, выполняя большие количества асинхронных задач, из-за уменьшенных издержек вызова на задачу, и они обеспечивают средство ограничения и управления ресурсами, включая потоки, использованные, выполняя набор задач. Каждый ThreadPoolExecutor также поддерживает немного основной статистики, такой как число завершенных задач.
Чтобы быть полезным через широкий диапазон контекстов, этот класс обеспечивает много корректируемых параметров и рычагов расширяемости. Однако, программистов убеждают использовать более удобное Executors методы фабрики Executors.newCachedThreadPool() (неограниченный пул потоков, с автоматическим восстановлением потока), Executors.newFixedThreadPool(int) (пул потоков фиксированного размера) и Executors.newSingleThreadExecutor() (единственный фоновый поток), которые предварительно конфигурируют настройки для наиболее распространенных сценариев использования.
Сколько способов создать нить вы знаете?
Исходя из этой дискуссии, поднятой на хабре, выходит, что нельзя.