简体   繁体   中英

Can I make Thread.stop() here?

I have this type and search functionality in my program.

There is a search method that takes some time to complete and should run on a separate thread and I should be able to kill it when the user type a new letter to make a new search but the problem is I use a third party trie implementation that doesn't check for interruptions and I read everywhere that using Thread.stop() will make bad impact on my program so my question is with this code down there will it be okay to use thread.stop()??? Or if there is any other way I can accomplish that?

 ArrayList search(key)
    {
        Map m = patricaTrie.prefixMap(key);  // 3rd party code cant be modified
        HashSet hs = new HashSet(m.size());
        ArrayList al = new ArrayList();
        for(Object t : collection)
        {
            if(!hs.contains(t))
            {
                al.add(t);
                hs.add(t);
            }
        }
        return al;
    }

Use signal handling in threads to stop a running thread gracefully. For example:

You can create a boolean field and check it inside run:

    public class Task implements Runnable {

       private volatile boolean isRunning = true;

       public void run() {

         while (isRunning) {
             //do work
         }
       }

      // public void kill() {
      //  isRunning = false;
      // }

    }

Now when you want to stop this running thread, just set the flag isRunning=false; to pass a signal indicating the thread to stop gracefully.

For the most part, the only "safe" way to kill a Thread is to code the Thread in such a way that it can receive a signal to stop. For example, use a boolean variable called shouldQuit and have the Thread periodically check that variable, quitting if it's true.

when the user type a new letter to make a new search set this boolean to true and get out of the run method.

Well, Thread.stop does not corrupt the JVM, however if you have not handled your code properly (ie leaving garbage data , leaving corrupted instances etc...), then some other area of your code that maybe referring the variables you have used in your stopped thread may get problems.

For example, if any variable, Object that you are using in the thread is being referenced outside of search() by your main thread, then since corrupted data is available in the Objects, your main thread may misbehave.

So it is advisable to make sure that you do not use any objects in the thread that your are stopping from outside, if you have to, then have a way of identifying if that object is corrupted or not.

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