当前位置:网站首页>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
边栏推荐
- Algorithem_ReverseLinkedList
- 倒计时1天~2022云容灾产品线上发布会即将开始
- On the problem of cliff growth of loss function in the process of training
- Recyclerview advanced use (I) - simple implementation of sideslip deletion
- RecyclerView进阶使用-实现仿支付宝菜单编辑页面拖拽功能
- gzip和gunzip 解压参数详解
- Jmeter设置环境变量支持在任意终端目录输入jmeter直接启动
- POI operation word template replaces data and exports word
- Check in system based on ibeacons
- MYSQL 主从同步避坑版教程
猜你喜欢
Jira截取全图
Wechat applet positioning and ranging through low-power Bluetooth device (2)
Cdh6 based on CM management 3.2 cluster integration atlas 2 one
Jmeter安装教程以及我遇到的问题的解决办法
RobotFramework 之 用例执行
org.apache.parquet.schema.InvalidSchemaException: A group type can not be empty. Parquet does not su
关于NodeJS中JSON5的相关配置和使用
帆软之单元格部分字体变颜色
Windos中安装labellmg教程
查询2013年到2021年的数据,只查询到2020的数据,遇到了这个问题所进行的解决办法
随机推荐
HyperBDR云容灾V3.3.0版本发布|容灾功能升级,资源组管理功能优化
基于CM管理的CDH集群集成Phoenix
什么是云迁移?云迁移的四种模式分别是?
OpenStack如何跨版本升级
Jacob print word
Some experience of using dialogfragment and anti stepping pit experience (getactivity and getdialog are empty, cancelable is invalid, etc.)
Wechat applet communicates with low-power Bluetooth - sending data to hardware (III)
服务器日志分析工具(识别,提取,合并,统计异常信息)
VMware15Pro在Deepin系统里面挂载真机电脑硬盘
VMware installation 64 bit XP Chinese tutorial
帆软实现分页时第一行和最后两行冻结方式
leetcode--357. Count the number of different figures
1到100号的灯开关问题
多云数据流转?云上容灾?年前最后的价值内容分享
Chrome插件 之 Selenium IDE、XPath 安装
帆软中根据分类进行汇总
回顾2021:如何帮助客户扫清上云最后一公里的障碍?
RecyclerView高级使用(二)-垂直拖拽排序的简单实现
pthread_ Why does self() repeat
JDBC和servlet写CRUD的接口总结