Can interrupt stop a thread?

The answer is not sure. It depends on the situation. Look at this test code

/**
 * Created by chen on 2018
 */
public class MyThread extends Thread {
    private static final String TAG = "duo_shine";
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(80);
            } catch (InterruptedException e) {
                Log.d(TAG, "InterruptedException : ");
            }
            Log.d(TAG, "Enumeration : " + i);
        }
        Log.d(TAG, "End of task");
    }
}

private void startThread() {
        mMyThread = new MyThread();
        mMyThread.start();
    }

    public void btn_test(View view) {
        mMyThread.interrupt();
    }

The result doesn't stop until I click stop or the whole method is finished. What if we are in a dead cycle? It won't stop

To ensure that the thread can stop, there are two ways to use the interrupt method in combination with return and catch

interrupt + catch stop thread

/**
 * Created by chen on 2018
 */
public class MyThread extends Thread {
    private static final String TAG = "duo_shine";

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(80);
                //Judge whether the thread is in stop state
                if (this.interrupted()) {
                    throw new InterruptedException();
                }
            } catch (InterruptedException e) {
                Log.d(TAG, "Interrupt task");
                return;
            }
            Log.d(TAG, "Enumeration : " + i);
        }
        Log.d(TAG, "End of task");
    }
}

As a result, the thread stops immediately after I click, and the code under the for loop will not be executed again

return+interrupt stop thread

/**
 * Created by chen on 2018
 */
public class MyThread extends Thread {
    private static final String TAG = "duo_shine";

    @Override
    public void run() {
        for (;;) {
        //Judge whether the thread is in stop state
            if (this.isInterrupted()) {
                Log.d(TAG, "Interrupt task");
                return;
            }
            Log.d(TAG, "Enumeration : ");
        }
    }
}

As a result, the thread stops immediately after I click

Posted by harmclan on Sun, 05 Jan 2020 23:20:10 -0800