개발일지

[Android] ConditionVariable 본문

Android

[Android] ConditionVariable

강강강 2021. 6. 29. 19:19

lock 기능을 갖는 변수

 

  • public boolean block(long timeout) - 변수 상태가 open 될 때 까지 또는 time out 될 때 까지 현재 스레드는 block 한다. time out 으로 인해 대기가 해제되었을 때 false 반환하고 다른 스레드에 의해 conditionvariable 가 오픈되었을 경우 true 를 반환한다. 
  • public void close() - conditionvariable 를 닫은 상태로 만든다. 닫힌 상태에서 block() 메소드를 호출한 모든 스레드는 모두 대기상태로 유지된다. 
  • public void open() - conditionvariable 을 오픈상태로 만든다. 닫힌 상태에서 block() 메소드를 호출한 모든 스레드는 conditionvariable 가 오픈된 상태가 되면 대기를 해제함\

스크래핑이 비동기이기 때문에 결과를 차례대로 나오게 하기 위해 block() 을 해줘 결과를 차례대로 받을 수 있다.

 

- 사용법 

ConditionVariable cond = new ConditionVariable();

protected String runScraping(JSONObject input){
        StringBuffer result = new StringBuffer();
        Scrapping sp = new Scrapping(context, input, (type, result) -> {
            if (type == KangSDK.KANG_EV_COMPLETE) {
                result.append(result.getResult());
                cond.open(); // 2. 완료 이벤트가 들어오면 open()
            }
        });
        KangSDK.run(sp);
        cond.block(2000000); // 1. run() 하는동안 멈춰있다가
        return result.toString();
    }

1. runScraping() 이 호출되고 KangSDK.run() 작업이 시작되면 block() 해 모든 스레드는 대기중에 있는다.

2. KangSDK.KANG_EV_COMPLETE 이라는 완료 이벤트가 들어오면 다시 open() 해 대기상태를 해제한다. 

https://developer.android.com/reference/android/os/ConditionVariable

 

ConditionVariable  |  Android Developers

 

developer.android.com

 

'Android' 카테고리의 다른 글

[Android] AAB; Android App Bundle  (0) 2021.06.29
[Android] Broadcast Receiver  (0) 2021.06.29
[Android] gradle  (0) 2021.06.29
[Android][Kotlin] Scope Function, Collections  (0) 2021.06.29
[Android] Observer Pattern / Event Bus  (0) 2021.06.29