0

I am working on Android Application which have service class. I service class, I have to start a thread. It is working fine. But I need to stop the thread. I have used with

mThread.destroy();
mThread.stop();

but both are deprecated and i have used

mThread.interrupt();

but it still does not work.

code

public void Receivepatientattributes(byte[] readBuf, int len) {

    if (readBuf[8] == 6){

                pktcount++;

                byte pkmsb = readBuf[11];
                byte pklsb = readBuf[10];
                int pkresult = (pkmsb << 8) | ((int)pklsb & (0x00FF));

                System.out.println("Packet : "+pktcount+"   :   "+pkresult);
                if(pkresult == pktcount){                    

                    for(int i = 0, j = 14; i < len ; i++, j++) {
                        queue.add(readBuf[j]);
                    }
                    if(mThread.getState() == Thread.State.NEW) {
                        mThread.start();
                        System.out.println("Start Thread ");

                    } else {
                        System.out.println("No Thread Found");
                    }

                } else {
                    displayToast("Packet Count Error");
                }
        }
    }
}
class CommunicationThread implements Runnable {

    @Override
    public void run() {

        do{
            if(queue.getFirst() == (byte)0x80) {
                System.out.println("absolu1 " + queue.getFirst());
                getabs_data();

            } 
        } while (queue.size() > 132);

        if(mThread.getState() == Thread.State.RUNNABLE) {
            mThread.interrupt();
        }
    }
}
Arya
  • 1,729
  • 3
  • 17
  • 35
  • http://www.ibm.com/developerworks/library/j-jtp05236/ is a nice article wrt interrupting threads correctly. – zapl Dec 02 '15 at 12:45

5 Answers5

0

Try with

if(mThread.isInterrupted()){
    break;
}

inside your loop.

Zhaosheng Qiu
  • 86
  • 1
  • 5
0

Java does not provide any ways to stop a thread safely, it only provides interruption

You can send interceptions to a thread, but this does not mean to kill a thread . Only if the target thread have the ability to respond to this interception, it can stop itself.

For example, the target have a loop to check whether or no it is interrupted. Or if the target thread call some interrupt-able blocking functions, you can check the interruption in your catch block and stop this thread.

For more information about java concurrency, read the book 《Java Concurrency in Practice》

VicX
  • 721
  • 8
  • 13
0

Thread objects are controlled by the system, which can modify them outside of your app's process. For this reason, you need to lock access on a thread before you interrupt it, by placing the access in a synchronized block.

ublic class PhotoManager {
public static void cancelAll() {
    /*
     * Creates an array of Runnables that's the same size as the
     * thread pool work queue
     */
    Runnable[] runnableArray = new Runnable[mDecodeWorkQueue.size()];
    // Populates the array with the Runnables in the queue
    mDecodeWorkQueue.toArray(runnableArray);
    // Stores the array length in order to iterate over the array
    int len = runnableArray.length;
    /*
     * Iterates over the array of Runnables and interrupts each one's Thread.
     */
    synchronized (sInstance) {
        // Iterates over the array of tasks
        for (int runnableIndex = 0; runnableIndex < len; runnableIndex++) {
            // Gets the current thread
            Thread thread = runnableArray[taskArrayIndex].mThread;
            // if the Thread exists, post an interrupt to it
            if (null != thread) {
                thread.interrupt();
            }
        }
    }
}
...

}

For Further reference use this link.

Dasrath
  • 366
  • 2
  • 11
androgo
  • 564
  • 2
  • 8
0

In CommunicationThread, there's a do... while loop. Edit this loop slightly by adding isInterrupted() to the loop's condition:

    do{
        if(queue.getFirst() == (byte)0x80) {
            System.out.println("absolu1 " + queue.getFirst());
            getabs_data();

        } 
    } while (mThread.isInterrupted() && queue.size() > 132);
Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87
0

It's not a good idea to use Threads in android. Because it's not Thread-safe. Instead, use AsyncTask, which android sdk provided for this purpose. FYI, for cancelling an AsyncTask you should call:

myAsyncTask.cancel(true);
Shayan_Aryan
  • 2,002
  • 1
  • 29
  • 31
  • 1
    Not true / oversimplified. `AsyncTask` itself is nothing more than a nicer way to use plain old `Thread`s. They are preferred when you implement the pattern they were meant for: tasks forked off from the main thread that need to report back to the main thread. `AsyncTask` provides a nice abstraction for the back and forth between main and background threads. They don't add any magic thread safety. – zapl Dec 02 '15 at 12:55