我想在主活动的下面代码中调用pauseThread方法 阻止currentcore整数计数。一些示例代码将不胜感激。如果那不可能,那么他们是否可以停止点击按钮?也许暂停线程?
public class ScoreThread extends Thread {
private boolean counter;
private int currentscore;
Handler scorehandler = new Handler();
private TextView playerscore;
ScoreThread(TextView v, Boolean b) {
playerscore = v;
counter = b;
}
public void pauseThread() throws InterruptedException {
counter = false;
}
public void resumeThread() throws InterruptedException {
counter = true;
}
public void run() {
currentscore = 0;
new Thread(new Runnable() {
@Override
public void run() {
while(counter == true) {
currentscore = currentscore + 1;
scorehandler.post(new Runnable() {
@Override
public void run() {
playerscore.setText("" + currentscore);
}
});
try{ Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}
}
}
}).start();
}
}
答案 0 :(得分:0)
您应该使用一个线程来执行计算。调用另一个线程是没用的。我简要介绍了如何实现目标
class Score extends Thread {
private boolean counter;
private int currentscore = 0;
public void stopThread() throws InterruptedException {
counter = false;
}
@Override
public void run() {
while (counter) {
currentscore = currentscore + 1;
//Do rest of your work
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
在你的主动作中 当你想开始计算时
Score score = new Score();
score.start();
当你想要停止线程时,例如从mainactivity调用线程的方法使用以下
try {
// your stop event
score.stopThread();
} catch (InterruptedException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}