简体   繁体   English

停止按名称运行线程

[英]Stop running Thread By Name

I have a multithreaded application and I assign a unique name to each thread through setName() property. 我有一个multithreaded应用程序,并且我通过setName()属性为每个线程分配了唯一的名称。

Now, I want functionality to get access to the threads directly with their corresponding name to stop it. 现在,我希望功能能够直接使用相应的名称访问线程以将其停止。

How can i get that? 我该怎么办?

To find a thread you use this: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ThreadUtils.html ( https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/ThreadUtils.java ) 要找到线程,请使用以下代码: https : //commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ThreadUtils.htmlhttps://github.com/apache/commons- lang / blob / master / src / main / java / org / apache / commons / lang3 / ThreadUtils.java

But that gives you only a reference to the thread and you cannot simply terminate it (stop() is deprecated). 但这仅给您一个对该线程的引用,您不能简单地终止它(不建议使用stop())。 Depending on what the Thread is doing maybe interrupting it is an option? 取决于线程正在做什么,也许可以中断它吗?

I assume you are trying to get to the thread (by its name) to call Thread.stop() on it. 我假设您正在尝试进入线程(按其名称)以在其上调用Thread.stop() If that is the case - don't do that. 如果是这种情况,请不要这样做。 The method is deprecated - see why . 不推荐使用此方法- 请查看原因

This question has some suggestions on how to properly stop a thread. 该问题对如何正确停止线程有一些建议。

If you really want to access a thread by name and you don't have a reference that can be used, you could use ThreadGroup and search the tree formed by groups and threads for the one with the correct name. 如果您确实想按名称访问线程,并且没有可使用的引用,则可以使用ThreadGroup并在由组和线程形成的树中搜索名称正确的线程。

From the JavaDoc: 从JavaDoc:

A thread group represents a set of threads. 线程组代表一组线程。 In addition, a thread group can also include other thread groups. 此外,线程组还可以包括其他线程组。 The thread groups form a tree in which every thread group except the initial thread group has a parent. 线程组形成一棵树,其中除初始线程组外的每个线程组都有一个父级。

Thus you should be able to call Thread.currentThread().getThreadGroup() , use getParent() to find the initial/root group, list all active threads using enumerate(Thread[]) and search the threads. 因此,您应该能够调用Thread.currentThread().getThreadGroup() ,使用getParent()查找初始/根组,使用enumerate(Thread[])列出所有活动线程并搜索线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM