当前位置:网站首页>ThreadGroup ThreadGroup implémente l'interface threadfactory en utilisant la classe Introduction + Custom thread Factory
ThreadGroup ThreadGroup implémente l'interface threadfactory en utilisant la classe Introduction + Custom thread Factory
2022-04-23 14:13:00 【Purluckyfish】
Un.、ThreadGroupIntroduction à la classe
Le Groupe thread est unStructure arborescente ,ThreadGroupLa classe a quelques façons de supprimer ou d'ajouter pour maintenir cet arbre,Il existe également des méthodes pour interroger l'état des noeuds d'arbre et les relations hiérarchiques;Du Groupe threadContrôle des droitsEtlinuxLe Groupe principal du genre est similaire à:Un thread n'est autorisé à accéder qu'à des informations sur son propre groupe de Threads,Mais l'accès aux informations du Groupe parent ou de tout autre groupe de thread du Groupe de thread dans lequel il réside n'est pas autorisé.
Exemple de code:
package com.yu;
public class ThreadGroupTest {
public static void main(String[] args) throws Exception {
ThreadGroup tg_parent = new ThreadGroup(" Groupe de thread parent ");
ThreadGroup tg_son = new ThreadGroup(tg_parent, " Sous - groupes de fils ");
Thread t1 = new Thread(tg_son, () -> {
System.out.println("Nom du thread:" + Thread.currentThread().getName());
System.out.println("Nom du Groupe de thread:" + Thread.currentThread().getThreadGroup().getName());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t1Thread");
Thread t2 = new Thread(tg_parent, () -> {
System.out.println("Nom du thread:" + Thread.currentThread().getName());
System.out.println("Nom du Groupe de thread:" + Thread.currentThread().getThreadGroup().getName());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t2Thread");
Thread t3 = new Thread(tg_parent, () -> {
System.out.println("Nom du thread:" + Thread.currentThread().getName());
System.out.println("Nom du Groupe de thread:" + Thread.currentThread().getThreadGroup().getName());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t2Thread");
System.out.println("Nom du Groupe de thread:"+t1.getThreadGroup().getName());
System.out.println(" Si le thread est dans un groupe de Threads donné :"+t1.getThreadGroup().parentOf(tg_parent));
System.out.println(" Si le thread est dans un groupe de Threads donné :"+t1.getThreadGroup().parentOf(tg_son));
System.out.println(" Nombre de Threads actifs dans le Groupe de Threads :"+tg_parent.activeCount());// C'est une évaluation
System.out.println(" Nombre de groupes de Threads actifs dans un groupe de Threads :"+tg_parent.activeGroupCount());// C'est une évaluation
System.out.println(" Priorité maximale du Groupe thread :"+t1.getThreadGroup().getMaxPriority());
}
}
Utiliser le scénario: 1 Grande tâche , Il peut être divisé en plusieurs sous - fils indépendants en parallèle , Tant que l'un des sous - fils remplit les conditions de la tâche , Même si la tâche est terminée ,Appelé threadGroup.interrupt() Méthodes D'autres sous - fils peuvent s'arrêter ;2 Grande tâche , Il peut être divisé en plusieurs sous - fils indépendants en parallèle , Enfin, attendez la fin de l'exécution de tous les sous - threads et continuez .
2.、ThreadFactoryIntroduction à l'interface
ThreadFactoryEst une interface,Un seulThread newThread(Runnable r) Méthodes;
La classe d'implémentation d'usine de Threads personnalisés produit des Threads selon certaines règles comme une ligne de montage d'usine ,Ces fils “ Ils ressemblent tous à ” ;
Personnaliser la classe d'implémentation de thread Factory , Vous pouvez suivre exactement quand et combien de Threads un pool de Threads a été créé , Vous pouvez également personnaliser le nom du thread ,Groupe,Priorité, Même définir directement tous les Threads comme des Threads gardiens . Vous pouvez définir l'état de tous les Threads dans le pool plus librement en personnalisant le pool de Threads .
Exemple de code:
package com.yu;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class ThreadFactoryTest {
public static void main(String[] args) throws Exception {
// Usine de thread personnalisée
ThreadFactory threadFactoryOwner = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("threadFactoryOwner-pool-" + t.getId());
t.setDaemon(true);// Définir comme démon
return t;
}
};
// Créer un pool de Threads en utilisant une usine personnalisée
ExecutorService executorService = Executors.newFixedThreadPool(10, threadFactoryOwner);
for (int i = 0; i < 10; i++) {
executorService.submit(() -> {
System.out.println("Nom du thread:" + Thread.currentThread().getName());
System.out.println(" Groupes de thread :" + Thread.currentThread().getThreadGroup());
System.out.println("ThreadID:" + Thread.currentThread().getId());
System.out.println("==========================================");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
Thread.sleep(2000);
}
}
}
JDK Classe d'implémentation par défaut de thread Factory : Spécifie la classe d'implémentation de thread Factory lors de la création d'un pool de Threads , Si non spécifié, utiliser JDKUsine de thread par défaut.

Trois、Le lien entre les deux
Vous pouvez utiliser le Groupe de thread spécifié lors de la personnalisation d'une classe d'implémentation d'usine de thread .
版权声明
本文为[Purluckyfish]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231406486413.html
边栏推荐
- Use of WiFi module based on wechat applet
- HyperMotion云迁移助力中国联通,青云完成某央企上云项目,加速该集团核心业务系统上云进程
- redis数据库讲解(四)主从复制、哨兵、Cluster群集
- 查询2013年到2021年的数据,只查询到2020的数据,遇到了这个问题所进行的解决办法
- Operation instructions of star boundary automatic text translator (advanced version)
- 更改plsql工具栏的图标大小
- redis数据库讲解二(redis高可用、持久化、性能管理)
- Mysql个人学习总结
- JDBC details
- rsync+inotify远程同步
猜你喜欢
01-NIO基础之ByteBuffer和FileChannel
在MAC上安装mysql
Wechat applet positioning and ranging through low-power Bluetooth device (2)
Win10 comes with groove music, which can't play cue and ape files. It's a curvilinear way to save the country. It creates its own aimpack plug-in package, and aimp installs DSP plug-in
Jmeter设置环境变量支持在任意终端目录输入jmeter直接启动
How QT designer adds resource files
多云数据流转?云上容灾?年前最后的价值内容分享
帆软调用动态传参的方法,在标题中设置参数
查询2013年到2021年的数据,只查询到2020的数据,遇到了这个问题所进行的解决办法
利用json-server在本地创建服务器请求
随机推荐
多云数据流转?云上容灾?年前最后的价值内容分享
VMware Workstation 无法连接到虚拟机。系统找不到指定的文件
Algorithem_ReverseLinkedList
Idea控制台乱码解决
线程间控制之CountDownLatch和CyclicBarrier使用介绍
快速安装mongodb
Switch usage (wechat applet)
Use of WiFi module based on wechat applet
Detailed tutorial on the use of smoke sensor (mq-2) (based on raspberry pie 3B +)
预览CSV文件
HyperBDR云容灾V3.2.1版本发布|支持更多云平台,新增监控告警功能
倒计时1天~2022云容灾产品线上发布会即将开始
How QT designer adds resource files
sql中出现一个变态问题
Mysql个人学习总结
Jira截取全图
拨开云雾synchronized使用五种方式介绍
Detailed tutorial on the use of setinterval timing function of wechat applet
获取线程返回值Future接口与FutureTask类使用介绍
JDBC details