2010/03/26 14:38

Looper + (Handler / Message)



Looper.Looper()
Looper객체가 생성될 때 MessageQueue도 같이 생성되며, 생성된 Looper(MessageQueue)객체는 currentThread에 묶인다.
final MessageQueue mQueue;
private Looper() {
        mQueue = new MessageQueue();
        mRun = true;
        mThread = Thread.currentThread();
}


Looper.loop()
public static final void loop() {
        Looper me = myLooper();//현재 thread의 Looper인스턴스를 불러온다.
        MessageQueue queue = me.mQueue;
        while (true) {
            Message msg = queue.next(); // might block//메세지를 하나 꺼내서
            //if (!me.mRun) {
            //    break;
            //}
            if (msg != null) {
                if (msg.target == null) {
                    // No target is a magic identifier for the quit message.
                    return;
                }
                if (me.mLogging!= null) me.mLogging.println(
                        ">>>>> Dispatching to " + msg.target + " "
                        + msg.callback + ": " + msg.what
                        );
                msg.target.dispatchMessage(msg);//Message가 가진 Handler를 실행
                if (me.mLogging!= null) me.mLogging.println(
                        "<<<<< Finished to    " + msg.target + " "
                        + msg.callback);
                msg.recycle();//Message는 Recycle pool로.
            }
        }
    }

Reference

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

Most interaction with a message loop is through the Handler class.



간단요약 : MessageHandler를 가지고 있으며, LooperMessageQueue에 있는 Message들을 차례차례 불러와 Handler를 실행시킨다.

2010/03/26 13:57

ThreadLocal : 같은 이름의 변수에 Thread마다 다른 값을 저장.

같은 변수를 통해, Thread마다 다른 값은 저장하기 위해 쓰인다.

ThreadLocal.set() 을 통해 object를 넘겨주면, ThreadLocal은 HashTable에 currentThread와 넘겨받은 object를 저장한다.

나중에 ThreadLocal.get()을 통해 메소드를 호출한 thrad에 해당하는 값을 되찾아 올 수 있다.

Looper의 예
static 멤버를 Instantiation, Process 내에서 Looper.sThreadLocal를접근할수 있으면서Thread마다 다른 값을 저장할수 있도록 구현.
private static final ThreadLocal sThreadLocal = new ThreadLocal();
public static final void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());
}

Android Reference

Implements a thread-local storage, that is, a variable for which each thread has its own value. All threads share the same ThreadLocal object, but each sees a different value when accessing it, and changes made by one thread do not affect the other threads. The implementation supports null values.

http://developer.android.com/reference/java/lang/ThreadLocal.html




1