마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

Threadpool과 AsyncTask 질문입니다.

0 추천

안녕하세요 초보개발자입니다.

다름이아니라 요즘 최적화에 관심이 많아 

Threadpooling 기법에 대해 공부를 하고 있습니다. 기존에 통신할 때  AsyncTask를 주로 사용했습니다.

테스트를 해보고 싶어 간단한 예제를 만들어보았습니다.

AsyncTask로 구현한 예제 Main.class

for (int i = 0; i < 1000; i++) {

new Task().execute();

}



public class Task extends AsyncTask<Void, Void, Void>{

private String[] arrText = { "111", "222", "333", "444" };



@Override

protected Void doInBackground(Void... params) {

// TODO Auto-generated method stub

return null;

}

@Override

protected void onPostExecute(Void result) {

// TODO Auto-generated method stub

super.onPostExecute(result);

Random r = new Random();

System.out.println(++gidx + ":myId:" + Thread.currentThread().getId());

System.out.println("arrText:" + arrText[Math.abs(r.nextInt()) % arrText.length]);

if (gidx == 1000) {

long etime = System.currentTimeMillis();

System.out.println(etime-stime+"초");

}

}

}

Threadpool class 예제

long stime = System.currentTimeMillis();

for (int i = 0; i < 1000; i++) {

// 테스트 쓰레드 1000개를 만들어서 콜한다.

new Thread(new Runnable() {

public void run() {

ThreadPoolTester t = new ThreadPoolTester();

t.process("system");

}

}).start();

;

}

long etime = System.currentTimeMillis();

System.out.println(etime-stime+"초");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

ThreadPoolTester.destroyTester();





public static class ThreadPoolTester {

private static final ExecutorService threadPool = Executors.newFixedThreadPool(30);



public static void initTest() {



}



public static void destroyTester() {

threadPool.shutdown();

}



private static int gidx = 0;

private String[] arrText = { "111", "222", "333", "444" };



public void process(String request) {

threadPool.execute(new Runnable() {

public void run() {

Random r = new Random();



System.out.println(++gidx + ":myId:" + Thread.currentThread().getId());

System.out.println("arrText:" + arrText[Math.abs(r.nextInt()) % arrText.length]);



}

});



}



}

테스트 결과 

 AsyncTask 는 평균 389ms

Threadpool는 스레드 3개로 했을 시 평균 945ms

10개로 했을 때 AsyncTask 와 비슷한 결과값이 나왔습니다.

 

여기서 제가 궁금한건 스레드가 적고 빠른 AsyncTask 가 더 효율적이라고 판단이 되는데

이 생각이 맞는 생각인지 궁금합니다...

잘 아시는분 조언 부탁드립니다.

안드로군 (450 포인트) 님이 2014년 5월 12일 질문
안드로군님이 2014년 5월 12일 수정
저도 이런부분이 많이 궁금합니다.

주로 asynctask의 경우를 사용하는게 익숙치 않아 대부분 Thread를 사용하여 구현 하였습니다.

위의 예제를 보면 new 부분 속도가 비용이 많이드는걸로 판단되는데 그게맞나요 ?

1개의 답변

+1 추천
 
채택된 답변

http://stackoverflow.com/questions/18480206/asynctask-vs-thread-in-android

Use AsyncTask for:

  1. Simple network operations which do not require downloading a lot of data
  2. Disk-bound tasks that might take more than a few milliseconds

Use Java threads for:

  1. Network operations which involve moderate to large amounts of data (either uploading or downloading)
  2. High-CPU tasks which need to be run in the background
  3. Any task where you want to control the CPU usage relative to the GUI thread
aucd29 (218,390 포인트) 님이 2014년 5월 12일 답변
안드로군님이 2014년 5월 12일 채택됨
...