2014-09-22 3 views
0

스레드가 진행률 표시 줄에 도달했을 때 진행률 표시 줄이 0에서 100에 이르면 중단 스레드 및 처리기가 필요하지만 progressStatus 값이 음수가되면 스레드를 중지하는 데 도움이됩니다. 진행 표시 줄이 0진행률 표시 줄이 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();  

답변

1

프로그램이 스레드 안전, 실제로 읽고 두 개의 서로 다른 스레드에서 변수 (progressStatus)를 작성, 당신은 그 일을 피해야하지 도달하거나 당신이 synchronized 블록을 사용해야 수행하려는 경우 . 난 당신이 기능 scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)ScheduledThreadPoolExecutor을 사용하는 것이 좋습니다

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

        } 
       } 
      }); 

또 다른 방법 : 문제를 해결하기 위해이 방법을 수행 할 수 있습니다. 뭔가 같은 :

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

관련 문제