调用中断并不会停止线程,但是只是一瞬间,线程继续,但是为什么呢? 我当前针对此问题的解决方案是使用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());
}
}
答案 0 :(得分:2)
当Thread.sleep
抛出InterruptedException
时(由于在睡眠中被中断),它将清除中断标志。如果您希望它以这种方式工作,则实际上应该处理InterruptedException
并使用catch
块来打破循环。