Kanika
Kanika

Reputation: 10708

Force kill a running thread

I am building an application in which in an activity, I am using 2 threads,

1-main thread,
2-other thread

Now in some circumstances I want to force kill another thread,so that only my main thread should work..

currently I am using it as:

if(other_thread!=null)
   other_thread.interrupt();

but in interrupt() method,when main thread completed its task,then other thread started doing its task..And my requirement is my application ends when main thread completed its task..So instead of using interrupt(),which steps I should follow to force kill this other_thread??

Upvotes: 1

Views: 3168

Answers (2)

Egor
Egor

Reputation: 40193

I won't recommend you using the interrupt() method or any other techniques of thread killing. If you have a thread with a while loop inside, you can control this thread by a boolean flag for the while condition. When you set the flag to false the thread just finishes its task. Then you can call thread.join() from your main thread to be sure that the other thread has finished execution. Hope this helps.

Here's a little example:

boolean flag = true;
Thread secondary = new Thread(new Runnable() {

    @Override
    public void run() {
        while (flag) {
        // do something
        }
    }
});
secondary.start(); //start the thread
flag = false; // this will force secondary to finish its execution
try {
    secondary.join(); // wait for secondary to finish
} catch (InterruptedException e) {
    throw new RuntimeException(e);
}

Upvotes: 3

Carnal
Carnal

Reputation: 22064

I assume you have a variable which makes the thread run while that condition is true or something similiar. You could make a method inside that thread, and set the variable to false or similiar in order to break the loop which makes the thread run.

Upvotes: 0

Related Questions