Thread.Interrupt()无法在Android中正常工作?

时间:2018-08-09 22:44:05

标签: java android multithreading

这是我的代码:

调用中断并不会停止线程,但是只是一瞬间,线程继续,但是为什么呢? 我当前针对此问题的解决方案是使用ArrayList管理线程,然后遍历ArrayList停止线程。虽然这行得通,但肯定不是很好。有人可以帮我吗?


EINVAL

Logcat输出:

private Thread thread;
private static final String TAG = "StoragePresenter";

public void refreshVolumes(boolean isRunning) {
    if (isRunning) {
        Handler handler = new Handler();
        Runnable runnable = () -> {
            while (!thread.isInterrupted()) {
                Log.d(TAG, "refreshVolumes: thread.isInterrupted? above while " + thread.isInterrupted());
                try {
                    Thread.sleep(refreshDelay);
                    Log.d(TAG, "refreshVolumes: in TRY ---> " + Thread.currentThread().getName()); //Thread -> 9
                } catch (InterruptedException ignored) {
                }
                Log.d(TAG, "refreshVolumes: in runnable WHILE ---> " + Thread.currentThread().getName());
                handler.post(this::getVolumes);
            }
        };
        thread = new Thread(runnable);
        Log.d(TAG, "refreshVolumes: start thread's name -> " + thread.getName());
        thread.start(); // Thread -> 9 started
    } else {
        Log.d(TAG, "refreshVolumes: interrupt thread's name -> " + thread.getName());
        thread.interrupt(); // Thread -> 9 interrupted
        Log.d(TAG, "refreshVolumes: thread.isInterrupted? " + thread.isInterrupted());
        Log.d(TAG, "refreshVolumes: thread.isInterrupted? 2x " + thread.isInterrupted());
    }
}

1 个答案:

答案 0 :(得分:2)

Thread.sleep抛出InterruptedException时(由于在睡眠中被中断),它将清除中断标志。如果您希望它以这种方式工作,则实际上应该处理InterruptedException并使用catch块来打破循环。