Android 线程和处理程序没有停止
Posted
技术标签:
【中文标题】Android 线程和处理程序没有停止【英文标题】:Android thread and handler are not stoping 【发布时间】:2021-09-07 09:23:19 【问题描述】:我在 android 中尝试了简单的代码,它每秒将 textView 更改为经过的秒数:
onCreate 方法:
Runnable runnable = new Wait(15);
sleep = new Thread(runnable);
sleep.start();
一个扩展 Thread 的新类:
class Wait extends Thread
int seconds;
Wait(int seconds)
this.seconds = seconds;
@Override
public void run()
for (int i = 1 ; i < this.seconds + 1; i++)
try
Thread.sleep(1000);
catch (InterruptedException e)
e.printStackTrace();
int finalI = i;
handler.post(new Runnable()
@Override
public void run()
textView.setText(finalI + "");
);
我正在尝试(没有任何成功)阻止它:
// onClick button method
sleep.interrupt();
为什么它不起作用? 它不会停止线程。它只是缩短了睡眠时间。之后,文本保持更改(循环继续运行)。
【问题讨论】:
你解决问题了吗? 【参考方案1】:打电话给
sleep.interrupt();
不要停止它just set thread's interrupt status and if this thread is blocked for example by Thread.sleep()
then its interrupt status will be cleared and it will receive an InterruptedException
. 的线程(关注链接以查看更多 deales)。
这就是为什么您每次都应该检查Thread.isInterrupted()
并在获得catch
块时完成run()
方法执行(例如,通过调用return
)获得InterruptedException
或创建您自己的标志来照亮线程中断.
您可以像这样更改您的代码:
@Override
public void run()
for (int i = 1 ; i < (this.seconds + 1) && !isInterrupted(); i++)
try
Thread.sleep(1000);
catch (InterruptedException e)
e.printStackTrace();
return;
int finalI = i;
handler.post(new Runnable()
@Override
public void run()
textView.setText(finalI + "");
);
或者用你自己的旗帜:
class Wait extends Thread
int seconds;
private volatile boolean iInterruptThisThread = false;
Wait(int seconds)
this.seconds = seconds;
public void interruptThreadMySelf()
iInterruptThisThread = true;
super.interrupt();
@Override
public void run()
for (int i = 1; i < (this.seconds + 1) && !iInterruptThisThread; i++)
try
Thread.sleep(1000);
catch (InterruptedException e)
e.printStackTrace();
if(iInterruptThisThread)
return;
int finalI = i;
handler.post(new Runnable()
@Override
public void run()
textView.setText(finalI + "");
);
class Wait extends Thread
int seconds;
private volatile boolean iInterruptThisThread = false;
Wait(int seconds)
this.seconds = seconds;
public void interruptThreadMySelf()
iInterruptThisThread = true;
super.interrupt();
@Override
public void run()
for (int i = 1; i < (this.seconds + 1) && !iInterruptThisThread; i++)
try
Thread.sleep(1000);
catch (InterruptedException e)
e.printStackTrace();
if(iInterruptThisThread)
return;
int finalI = i;
handler.post(new Runnable()
@Override
public void run()
textView.setText(finalI + "");
);
然后拨打sleep.interruptThreadMySelf()
顺便说一句,您可以使用sleep = new Wait(15);
而不是sleep = new Thread(runnable);
。
【讨论】:
以上是关于Android 线程和处理程序没有停止的主要内容,如果未能解决你的问题,请参考以下文章