简体   繁体   English

如何多次命名线程并在Java中使用它

[英]How to name a Thread multiple times and use it in Java

I have a class which has a runnable thread in it. 我有一个其中具有可运行线程的类。 I send a variable to this class more than one time at the same time. 我一次不只一次将变量发送给此类。 The class has run() method and starts own thread for the variable sent from another class. 该类具有run()方法,并为从另一个类发送的变量启动自己的线程。 After some processes, i need to stop Threads with interrupt but i have to spesify the name of the thread that i want to stop (such as MyThread.interrupt() ). 经过一些处理后,我需要使用中断来停止线程,但是我必须具体化要停止的线程的名称(例如MyThread.interrupt())。 The problem is, i create the thread with the same object name in the class everytime. 问题是,我每次在类中创建具有相同对象名称的线程。 So i have to name this thread object differently every time and stop it by its name. 因此,我每次都必须以不同的方式命名该线程对象,并以其名称停止它。 But i dont know how to.. This is my code; 但是我不知道该怎么做。

public class KasaThread  {

public static Thread till ;

public static String [] table_list_kasa; 


public  static void get (final String IP,final String MagID){


     till = new Thread () {



            public void run () {


                if(IP != null){


                try{
                    ...
                    ...
                    ...
                    }catch(Exception e} {}

in another class, I interrupt this thread by its name like (till.interrupt() ).. But as i said, every thread which is created in this class, has the same name (till). 在另一个类中,我使用(till.interrupt())之类的名称来中断该线程。但是正如我所说,在该类中创建的每个线程都具有相同的名称(直到)。

How to solve this ? 如何解决呢?

Thanks in advance. 提前致谢。

我认为您可以使用方法 setName(String name)getName() +一些计数器来解决此问题。

一种解决方案是在另一个类中保存一个HashMap(或您喜欢的线程的其他任何ID),并使其实现Runnable,以便您可以在另一个类中控制线程。

You could put the threads in an ArrayList or LinkedList . 您可以将线程放入ArrayListLinkedList If you actually want to be able to access them by name, you could use a Map<String, Thread> for that. 如果您实际上希望能够按名称访问它们,则可以使用Map<String, Thread>

Do you want to stop all threads at the same time? 是否要同时停止所有线程? If so, you could add a stop() method to the class for that. 如果是这样,您可以为此添加一个stop()方法。 It would probably look like this: 它可能看起来像这样:

public void stop() {
    for (Thread thread : threads) {
        thread.interrupt()
    }
}

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

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