티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Android basics: running code in the UI thread

안드로이드 기초: UI 스레드에서 코드 실행하기

 문제 내용 

In the viewpoint of running code in the UI thread, is there any difference between:

UI 스레드에서 코드를 실행하는 관점에서, 다음 두 가지 방법 사이에 차이가 있습니까?
MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        Log.d("UI thread", "I am the UI thread");
    }
});

 

or

혹은
MainActivity.this.myView.post(new Runnable() {
    public void run() {
        Log.d("UI thread", "I am the UI thread");
    }
});

 

and

 그리고
private class BackgroundTask extends AsyncTask<String, Void, Bitmap> {
    protected void onPostExecute(Bitmap result) {
        Log.d("UI thread", "I am the UI thread");
    }
}

 

 

 높은 점수를 받은 Solution 

None of those are precisely the same, though they will all have the same net effect.

위의 것들은 정확히 같지는 않지만, 모두 같은 효과를 가질 것입니다.

 

The difference between the first and the second is that if you happen to be on the main application thread when executing the code, the first one (runOnUiThread()) will execute the Runnable immediately. The second one (post()) always puts the Runnable at the end of the event queue, even if you are already on the main application thread.

첫 번째와 두 번째의 차이점은 코드 실행 시 메인 애플리케이션 스레드에서 실행 중인 경우 첫 번째(runOnUiThread())는 Runnable을 즉시 실행한다는 것입니다. 두 번째(post())는 메인 애플리케이션 스레드에서 이미 실행 중인 경우에도 Runnable을 이벤트 큐의 끝에 넣습니다.

 

The third one, assuming you create and execute an instance of BackgroundTask, will waste a lot of time grabbing a thread out of the thread pool, to execute a default no-op doInBackground(), before eventually doing what amounts to a post(). This is by far the least efficient of the three. Use AsyncTask if you actually have work to do in a background thread, not just for the use of onPostExecute().

세 번째 방법인 BackgroundTask를 생성하고 실행하는 경우, 기본적으로 no-op(doInBackground()가 실행되지 않음)를 실행하고 나서 post()를 실행하므로 많은 시간을 쓰레드 풀에서 쓰레드를 가져와 사용하게 됩니다. 이는 세 가지 방법 중에서 가장 효율적이지 않습니다. 만약 실제로 백그라운드 스레드에서 할 일이 있는 경우에만 AsyncTask를 사용하며, onPostExecute()를 사용할 목적으로만 사용하지 않도록 해야한다.

 

 

 

 가장 최근 달린 Solution 

use Handler

Handler를 사용하세요.
new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        // Code here will run in UI thread
    }
});

 

 

출처 : https://stackoverflow.com/questions/12850143/android-basics-running-code-in-the-ui-thread

반응형
댓글
공지사항
최근에 올라온 글