How to cancel a thread

2019-04-15 11:53发布

问题:

I am trying to make a media player which has a seekbar. As the seekbar should stop progress when pause is pressed or stop is pressed. I want to stop the thread accordingly. Moreover when back is pressed I want to cancel the thread again.

回答1:

Use Thread.currentThread().interrupt()

Thread interruption

Every thread has a Boolean property associated with it that represents its interrupted status. The interrupted status is initially false; when a thread is interrupted by some other thread through a call to Thread.interrupt(), one of two things happens. If that thread is executing a low-level interruptible blocking method like Thread.sleep(), Thread.join(), or Object.wait(), it unblocks and throws InterruptedException. Otherwise, interrupt() merely sets the thread's interruption status. Code running in the interrupted thread can later poll the interrupted status to see if it has been requested to stop what it is doing; the interrupted status can be read with Thread.isInterrupted() and can be read and cleared in a single operation with the poorly named Thread.interrupted().

Interruption is a cooperative mechanism. When one thread interrupts another, the interrupted thread does not necessarily stop what it is doing immediately. Instead, interruption is a way of politely asking another thread to stop what it is doing if it wants to, at its convenience. Some methods, like Thread.sleep(), take this request seriously, but methods are not required to pay attention to interruption. Methods that do not block but that still may take a long time to execute can respect requests for interruption by polling the interrupted status and return early if interrupted. You are free to ignore an interruption request, but doing so may compromise responsiveness.

One of the benefits of the cooperative nature of interruption is that it provides more flexibility for safely constructing cancelable activities. We rarely want an activity to stop immediately; program data structures could be left in an inconsistent state if the activity were canceled mid-update. Interruption allows a cancelable activity to clean up any work in progress, restore invariants, notify other activities of the cancellation, and then terminate.



回答2:

boolean running = true;
final Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            while(running){
                 //Your code
            }
        } catch (Exception e) {
        // TODO Auto-generated catch block
    e.printStackTrace();
    }
    //handler code

    }
});
t.start();

defining a "running" boolean will manage when the thread will execute its code, when you set running to false the seekbar will stop without interrupting or killing the thread.