Java 在android中,当进度条达到0时,我需要停止线程
当我的进度条从100达到0时,我需要停止线程和处理程序。当线程运行时,进度条达到0,但progressStatus值为负值。请帮助我在进度条达到0后停止线程Java 在android中,当进度条达到0时,我需要停止线程,java,android,multithreading,Java,Android,Multithreading,当我的进度条从100达到0时,我需要停止线程和处理程序。当线程运行时,进度条达到0,但progressStatus值为负值。请帮助我在进度条达到0后停止线程 new Thread(runn =new Runnable() { public void run() { while (progressStatus <= 100) { progressStatus += doWork(); try {
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();
新线程(runn=newrunnable(){
公开募捐{
虽然(progressStatus您的程序不是线程安全的,但实际上您从两个不同的线程读取和写入变量(progressStatus)
,必须避免这样做,或者如果您想这样做,必须使用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命令,长initialDelay,长周期,时间单位)
一起使用
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);
要关闭它,请使用myTimer.shutdownNow();