2016-12-23 2 views
-3

기본적으로 각 사용자마다 5 개의 Runnables가 있습니다.Android : Runnable 내의 Runnable

각 Runnable 안에 변수가 변경 될 때까지 기다려야합니다. 나는 Semaphore 나 CountDownLatch를 사용할 것이다.

그래서 각 Runnable 내부에는 대기중인 runnable이 있습니다.

다음은 예입니다. r1은 사용자이기 때문에 끝내지 않는 실행 파일입니다.

final Handler handler = new Handler(); 
Runnable r1 = new Runnable() { 
    @Override public void run() { 

      // here must be another runnable for waiting 
       Runnable r2 = new Runnable() { 
        @Override public void run() { 

         if (condition) { 
          latch.countDown(); 
          // ending the runnable 
           handler.removeCallbacks(r2); 
         } else { 
          // keep waiting 
          handler.postDelayed(r2, 1000); 
         } 
        } 
       } 

      latch.await(); 
     // restarting the runnable 
     handler.postDelayed(r1, 1000); 
    } 
} 

latch.await()을 사용할 때의 문제점은 UI를 차단하는 주 스레드에서 실행 중입니다.

다른 스레드에서 실행하는 방법을 알기 원하십니까?

+0

왜 세계에 당신이 그들을 중첩하고 있습니까 ??? – Chisko

+0

실제로 달성하고자하는 것은 무엇입니까? – pskink

+0

[중첩 된 postDelayed/Runnable/Handler Android]의 가능한 복제본 (http://stackoverflow.com/questions/11197543/nested-postdelayed-runnable-handler-android) – Chisko

답변

0

내가 원했던 부분은 변수를 변경하기 위해 기다릴 필요가있는 논스톱 실행 스레드입니다. 그래서 다른 명령을 계속합니다. 버튼을 클릭 할 때 UI의 다른 곳에서 세마포어가 증가합니다. 그리고 스레드에서 사용할 수있을 때까지 기다립니다. 여기에 내가 만든 해결책이있다

Semaphore sem = new Semaphore(0,true); 
//somewhere in UI sem.release(); 

Thread thread = new Thread() 
     { 
      @Override 
      public void run() { 
       try { 
        while(true) { 
         sleep(1000); 

         semaphore.acquire(); 

         // when updating the UI is needed 
         runOnUiThread(new Runnable() { 
          @Override 
          public void run() { 
           // work 
          } 
         }); 


        } 
       } catch (InterruptedException e) { 

       } 
      } 
     }