2014-09-22 50 views
0

我需要停止線程和處理程序時,當我的進度條從100到達0時,線程運行進度條到達,但progressStatus值進入負面請幫我停止線程後進度條達到0我需要停止線程時進度條達到0在android

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();  

回答

1

你的程序是不是線程安全,你居然讀,從兩個不同的線程書寫變量(progressStatus),你必須避免這樣做,或者如果你想這樣做,你必須使用​​塊。爲了解決你的問題,你可以做到這一點的方法:

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); 

,並以關閉它使用myTimer.shutdownNow();