안드로이드 멀티스레드

-- Android 2015. 7. 30. 11:22
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
안드로이드 앱을 만들다가 처리시간이 많이 소요되는 부분이 있어 멀티스레드를 고려하였다.
멀티스레드를 위해 AsyncTask를 아래와 같이 구현하였다.

 

AsyncTask < Params, Progress, Result >

Params : the type of the parameters sent to the task upon execution.
Progress : the type of the progress units published during the background computation.
Result : the type of the result of the background computation.
 

for(int i = 0; i < 5; i++) {
    new MyTask().execute();
}


그런데 싱글스레드로 돌리는 것보다 시간이 더 걸리는 것이다.
검색해보니 3.2 (허니콤)부터 AsyncTask의 기본이 직렬처리 (한 테스크가 끝나야 다음 테스트가 실행)로 변경되어 병렬처리를 위해서는 다른 방식이 필요하다.

for(int i = 0; i < 5; i++) {
    new MyTask().executeOnExcutor(AsyncTask.THREAD_POOL_EXECUTOR);
}


LOGCAT으로 봤을 때 분명 멀티스레드로 동작함을 확인할 수 있었다.
그러나 처리시간 소요가 확연히 줄어들지 않았다.
다른 방법을 검색하다가 ExecutorService라는 것을 발견하여 구현해 보았다.

ExecutorService concurrentService = Executors.newFixedThreadPool(5);
for(int i = 0; i < 5; i++) {
  concurrentService.submit(new MyThread("thread param"));
}

public class MyThread implements Callable<List<String>>
{
  public MyThread(String param) {
    ..
  }

  public List<String> call() throws Exception {
    ....
    return stringList; // List<String>형식의 결과값 리턴
  }
}

List<Future<List<String>>> results = new ArrayList<Future<List<String>>>(); // 결과를 리턴받을 객체를 생성
results.add(concurrentService.submit(new MyThread("threa param"))); // 스레드를 submit할 때 결과객체를 얻어냄
List<String> ret = ((Future<List<String>>)results.get(0)).get(); // 결과객체로부터 결과값을 받음


테스트 결과 AsyncTask보다 유연하게 멀티스레드를 돌릴 수 있었으나, 처리시간 소요가 아직 줄어들지 않았다.
각 스레드에서 Paint의 breakText()를 돌리는데 이 부분에서 절대적인 시간을 차지하고 있었다.
이론적으로는 breakText()를 하는 부분을 위의 예처럼 5개의 스레드에서 각각 실행하는데, 싱글스레드로 돌리는 것에 비해 소요시간이 비슷하거나 오히려 더 걸리는 것이 이해가 가지 않는다.

추후 이 부분에 대해 확인이 된다면 이 스레드에 업데이트 하겠다.

posted by 어린왕자악꿍