简体   繁体   中英

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. 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() ). 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).

How to solve this ?

Thanks in advance.

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

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

You could put the threads in an ArrayList or LinkedList . If you actually want to be able to access them by name, you could use a Map<String, Thread> for that.

Do you want to stop all threads at the same time? If so, you could add a stop() method to the class for that. It would probably look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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