我有一个带有3个按钮的活动:创建,开始和取消。按钮创建将创建一个新线程,按钮启动将运行该线程,按钮取消将停止该线程。我的问题是调用中断方法后,线程没有被中断(单击取消按钮后执行此操作)。我知道,在我的线程中,我应该检查线程是否中断。我添加了它,但打断仍然不起作用。这是我的代码:
private View.OnClickListener listener = new View.OnClickListener() {
@SuppressLint("HandlerLeak")
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.create_button:
thread = new Thread(new Runnable() {
@Override
public void run() {
int i;
for (i = 0; i<10;i++){
final int finalI = i;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
textCounter.post(new Runnable() {
@Override
public void run() {
textCounter.setText(String.valueOf(finalI));
}
});
}
}, 500*i);
if (thread.isInterrupted()){
Log.i(getClass().getSimpleName(), "Thread is interrupted");
return;
}
}
new Handler().postDelayed(new Runnable() {
@SuppressLint("SetTextI18n")
@Override
public void run() {
textCounter.setText("Done!");
}
},(i+1)*500);
}
});
break;
case R.id.start_button:
thread.run();
break;
case R.id.cancel_button:
thread.interrupt();
Log.i(getClass().getSimpleName(), "Cancel Button clicked");
break;
}
}
};
那么,为什么线程不被中断,我该如何解决这个问题?
答案 0 :(得分:2)
Your thread is quickly adding 11 tasks (10 + the last one) to this handler you're creating and then dying. These tasks have a delay, and then the message queue will take care of running the 10 + 1 runnables. To do what you're trying to do you should make the thread to wait 500ms between each loop.
Something similar to this:
thread = new Thread(new Runnable() {
@Override
public void run() {
int i;
for (i = 0; i<10;i++){
final int finalI = i;
textCounter.post(new Runnable() {
@Override
public void run() {
textCounter.setText(String.valueOf(finalI));
}
});
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
Log.i(getClass().getSimpleName(), "Thread is interrupted");
return;
}
if (thread.isInterrupted()){
Log.i(getClass().getSimpleName(), "Thread is interrupted");
return;
}
}
textCounter.post(new Runnable() {
@Override
public void run() {
textCounter.setText("Done!");
}
});
}
});
答案 1 :(得分:2)
您的代码有很多问题
问题1::当用户单击 Create 按钮时,您将创建一个新线程,这不是您期望的行为,因此,如果需要,只需创建一个新线程尚未创建或终止。
问题2::当用户单击开始按钮
时my.name <- readline(prompt="Enter name: ")
my.age <- readline(prompt="Enter age: ")
# convert character into integer
my.age <- as.integer(my.age)
print(paste("Hi,", my.name, "next year you will be", my.age+1, "years old."))
此行不启动线程,它仅在调用线程(在本例中为main / UI线程)上执行thread.run();
方法中的代码。要启动线程,必须使用run
方法。确保已启动线程(如果已创建)。
问题3::当用户单击取消按钮
时start
因为没有启动线程,所以此行无济于事。
问题4:根据您的描述,您想使用一个线程将TextView上的计数器每0.5秒从0增加到9,然后显示“完成”。您的代码不正确,并且包含许多冗余代码。
解决方案::您可以遵循以下代码。
thread.interrupt();