gpt4 book ai didi

java - 如何一键停止两个可运行程序?

转载 作者:行者123 更新时间:2023-12-02 07:39:21 25 4
gpt4 key购买 nike

我在尝试使用一个停止按钮停止两个可运行程序时遇到问题,我可以只停止两个中的一个,但一旦我尝试停止两个可运行程序,当在手机上按下按钮时,我的应用程序就会卡住,这是我到目前为止的代码:

    if(go != 1){
go = 1;
final Timer t =new Timer();
t.schedule(new TimerTask() {

@Override
public void run() {
runOnUiThread(new Runnable() {

public void run() {
if(DHPDPS==0){
money = (DPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
}else if(counter > DHPDPS && DOTPPS != 0 && DHPDPS != 0){
money = (DOTPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
} else{

money = (DPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
}
//Place your stopping condition over here. Its important to have a stopping condition or it will go in an infinite loop.
counter++;

// Display pay per second
if(counter <= DHPDPS || DHPDPS == 0){
t2.setText("Your pay per second is: $"+result);
}else{
t2.setText("Your pay per second is: $"+result2);
}
}
});
}
}, 20, 20);

// Make countdown to overtime display
final TextView count = (TextView) findViewById(R.id.countdown);
countdown = (int)HPDPS;
cd.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
public void run(){
int hours = (countdown/3600);
if(OTPPS != 0 && HPDPS != 0){
count.setText("Seconds Remaining to Overtime: " + countdown + "\nAbout " + hours + " Hours");
countdown--;
}
}
});
}

}, 1000, 1000);



final Button b = (Button) findViewById(R.id.clockout);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(go == 1)
go = 0;
if (t != null)
t.cancel();
// if (cd != null) // This condition Freezes my phone when activated?
// cd.cancel();
}
});

}

}

任何帮助将不胜感激!谢谢。

最佳答案

public void run() {
while(running) {
//your code for both runnables
}
}

final Button b = (Button) findViewById(R.id.clockout);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(running) {
running = false;
}
}
});

使用此代码,您的可运行对象将检查它们是否应该运行每个循环,如果不运行,它们将退出 run() 并且线程将停止。

关于java - 如何一键停止两个可运行程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11795352/

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