gpt4 book ai didi

java - 我如何在Android中停止线程

转载 作者:行者123 更新时间:2023-12-03 13:19:16 25 4
gpt4 key购买 nike

我试图制作一个倒数计数器,其中用户单击按钮即可停止倒数。

我在互联网上搜索了一种方法来停止控制倒数的线程。

我尝试使用interruptInterruptedstop,但是使用任何这些方法都无法成功停止线程。

问题:
如何停止控制倒数计数器的线程?

public class Main2Activity extends AppCompatActivity {

TextView mTextField;
Button stop;
Activity myActivity;
PrimeThread T1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
myActivity=this;
mTextField = (TextView) findViewById(R.id.counter);
T1=new PrimeThread();
T1.start(); }

public void stop(View view){ T1.interrupt(); }

class PrimeThread extends Thread {
int i=10;
public void run() {
while(i>0){
myActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mTextField.setText("00:0"+i);
}
});
i--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}}}
}

最佳答案

您可以在线程中放置一个标志:

public class Main2Activity extends AppCompatActivity {

TextView mTextField;
Button stop;
Activity myActivity;
PrimeThread T1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
myActivity=this;
mTextField = (TextView) findViewById(R.id.counter);
T1=new PrimeThread();
T1.start(); }

public void stop(View view){ T1.stopRunning(); }

class PrimeThread extends Thread {
int i=10;
boolean running = false;
public void run() {
running = true;
while(running && i < 10){
i++;
myActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mTextField.setText("00:0"+i);
}
});
i--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void stopRunning(){
running = false;
}
}
}

关于java - 我如何在Android中停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39185677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com