user2408952
user2408952

Reputation: 2041

looking for a way to stop/kill a Thread

I'm looking for a way to stop/kill a Thread, i saw that Thread.stop() is deprecated. So i started searching for another solution and saw multiple posts suggesting this:

thread.interrupt();
thread = null;

But that just won't stop my Thread, my Thread looks like this:

public static Thread loadingSpinnerTimer (final Context context, final ImageView imageView){
    final Handler mHandler = new Handler();
    thread = new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (!isPaused) {
                try {
                    Thread.sleep(100);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            // Write your code here to update the UI.
                            Log.e("ThreadMessage","HasRun");
                            if (ticker == 12){
                                ticker = 0;
                            }
                            Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.spinner_160x160);
                            Bitmap img = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.ARGB_8888); //ARGB_8888 transparrent?
                            Canvas canvas = new Canvas(img);
                            int offset = myBitmap.getWidth()*ticker;
                            Rect srcrectangle = new Rect( 0, offset, myBitmap.getWidth(), myBitmap.getWidth()+offset);
                            Rect dstrectangle = new Rect( 0, 0, myBitmap.getWidth(), myBitmap.getWidth());
                            canvas.drawBitmap(myBitmap,srcrectangle,dstrectangle,null);
                            img.setHeight(myBitmap.getWidth());
                            imageView.setImageDrawable(new BitmapDrawable(context.getResources(), img));
                            ticker++;
                        }
                    });
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
    });
    thread.start();
    return thread;
}

Anyone get a solution i can use to stop/kill my Thread? Any help is much appreciated.

Upvotes: 0

Views: 79

Answers (3)

PeterK
PeterK

Reputation: 1723

If you use thread.interrupt(); you should occasionally check if your Thread was interupted using something like:

if(Thread.currentThread().isInterrupted()) {
   return;
}

Note that checking this flag resets it; so that if you ever check for this flag your should either:

Terminate your thread

  1. List item
  2. Throw an InterruptedException
  3. Reset the flag by calling Thread.currentThread().interrupt();

Upvotes: 0

Jean Logeart
Jean Logeart

Reputation: 53879

Since you periodically execute a task, a good solution is to use a ScheduledExecutorService.

Then the scheduled task can be elegantly stopped calling cancel() on the ScheduledFuture<?>:

final Runnable handlerRunnable = new Runnable() {
    @Override
    public void run() {
        // do same work as before
    }
};
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
final Handler mHandler = new Handler();
ScheduledFuture<?> sf = ses.scheduleWithFixedDelay(new Runnable() {
    @Override
    public void run() {
        mHandler.post(handlerRunnable);
    }
}, 0, 100, TimeUnit.MILLISECONDS); // execute every 100ms

// stop
sf.cancel();

Upvotes: 0

evanwong
evanwong

Reputation: 5134

You have a while loop and checking isPaused and then catching the general Exception at the end of the loop. Even if the InterruptedException is thrown, it will be caught and then re-run the while loop again.

You will need to change the isPaused to true when you catch the InterruptedException exception so that the while loop will stop running.

Upvotes: 1

Related Questions