简体   繁体   中英

How to stop the thread on Android?

I have a function parseData which recieves Vector of urls and gives them to DataParser. DataParser gets data from urls and parses it. The problem is that user might request new urls to parse before previous parsingis finished. In that case previous data becomes irrelivant but thread continues to work. Since there might be a lot of urls in one request and parsing each of them takes time, after 5-6 sequential requests phone starts work very slowly.

Here is the code snippet.

public void parseData(final String key, final Vector<String> data)
{
    this.key = key;
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            DataParser dp = new DataParser(key);
            dp.setData(data);
            dp.startParse();
        }
    });
    thread.start();
}

I think the solution might be to keep extra flag in DataParser. Since it requesting urls in cycle, I can check flag and break cycle, but it seems to me rude.

Are there other ways to solve this issue?

You can use interrupt() method:

thread.interrupt();

BTW, checking some kinds of flags isn't so rude and bad style. But don't forget to declare such flag as volatile .

You need to check periodically for a flag in worker thread. Set that flag if worker thread is to be stopped.

You could constantly check on a boolean flag every time you perform a parsing operation, and stop parsing if this flag becomes true.

From another thread, you can establish the value of this flag to "cancel" the parsing.

This is the technique AsyncTasks use to cancel the work done in doInBackground().

class DataParser {
   private boolean volatile mIsCancelled = false;

   public void startParsingAsync() {
       new Thread(new Runnable(
                 public void run() {
                      parse();
                 } 
       )).start();
   }

   private void parse() {
          while(!isCancelled()) {
              parseNextNode();
          }
   }

   private synchronized void isCancelled() {
        return mIsCancelled();
   }

   public synchronized void cancel() {
       mIsCancelled = true;
   }

   private void parseNextNode() {
     .....
   }

From another thread, you can invoke the method cancel() once the data has become irrelevant.

Note the you have to synchronize the access to the flag, as it will be accessed from different threads.

This code is not tested, so it may not even compile...

That's the theory, but for practical uses, you should use an AsyncTask, which gives the cancelling for you.

This kind of thing is done well in an Async Task instead of straight thread. There is a cancel method to them and an is canceled function that can tell you to stop.

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