当线程运行进度条到达时,我的进度条从100变为0时需要停止线程和处理程序但是progressStatus值为负,请帮助我在进度条达到0后停止线程
new Thread(runn =new Runnable() {
public void run() {
while (progressStatus <= 100) {
progressStatus += doWork();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
handler.post(runn1=new Runnable() {
public void run() {
bar.setProgress(progressStatus);
i=-1;
if(bar.getProgress()==0)
{
handler.removeCallbacks(runn);
handler.removeCallbacks(runn1);
System.out.println("Reached");
congrats.setVisibility(View.VISIBLE);
restart.setVisibility(View.VISIBLE);
rightbutton.setVisibility(View.GONE);
wrongbutton.setVisibility(View.GONE);
}
}
});
}
}
private int doWork() {
return i;
}
}).start();
答案 0 :(得分:1)
你的程序不是线程安全,你实际上是从两个不同的线程读取和编写变量(progressStatus)
,你必须避免这样做,或者如果你想这样做,你必须使用{ {1}}阻止。为了解决您的问题,您可以这样做:
synchronized
我建议您采用另一种方式Thread t;
progressStatus = 100;
t = new Thread(runn =new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
// Update the progress bar
handler.post(runn1=new Runnable() {
public void run() {
bar.setProgress(progressStatus);
progressStatus=progressStatus-1;
if(bar.getProgress()==0)
{
handler.removeCallbacks(runn);
handler.removeCallbacks(runn1);
System.out.println("Reached");
congrats.setVisibility(View.VISIBLE);
restart.setVisibility(View.VISIBLE);
rightbutton.setVisibility(View.GONE);
wrongbutton.setVisibility(View.GONE);
t.interrupt();
}
}
});
使用函数ScheduledThreadPoolExecutor
。类似的东西:
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
要关闭它,请使用final ScheduledThreadPoolExecutor myTimer = new ScheduledThreadPoolExecutor(1);
myTimer.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
getActivity().runOnUiThread(new Runnable(){
@Override
public void run(){
}
});
}
}
}, 0,10, TimeUnit.MILLISECONDS);