77

我有一个位于后台的工作线程,处理消息。像这样的东西:

class Worker extends Thread {

    public volatile Handler handler; // actually private, of course

    public void run() {
        Looper.prepare();
        mHandler = new Handler() { // the Handler hooks up to the current Thread
            public boolean handleMessage(Message msg) {
                // ...
            }
        };
        Looper.loop();
    }
}

从主线程(UI线程,没关系)我想做这样的事情:

Worker worker = new Worker();
worker.start();
worker.handler.sendMessage(...);

麻烦的是,这为我设置了一个漂亮的竞争条件:在worker.handler读取时,无法确定工作线程已经分配给这个字段!

我不能简单地HandlerWorker的构造函数中创建,因为构造函数在主线程上运行,所以Handler会与错误的线程相关联。

这似乎并不罕见。我可以想出几个解决方法,所有这些都很难看:

  1. 像这样的东西:

    class Worker extends Thread {
    
        public volatile Handler handler; // actually private, of course
    
        public void run() {
            Looper.prepare();
            mHandler = new Handler() { // the Handler hooks up to the current Thread
                public boolean handleMessage(Message msg) {
                    // ...
                }
            };
            notifyAll(); // <- ADDED
            Looper.loop();
        }
    }
    

    从主线程:

    Worker worker = new Worker();
    worker.start();
    worker.wait(); // <- ADDED
    worker.handler.sendMessage(...);
    

    但这也不可靠:如果notifyAll()发生在 之前wait(),那么我们将永远不会被唤醒!

  2. 将初始值传递MessageWorker的构造函数,让run()方法发布它。临时解决方案不适用于多条消息,或者如果我们不想立即发送,但很快就会发送。

  3. 等到handler田野不再忙碌null。是的,最后的手段...

我想创建一个HandlerMessageQueue代表Worker线程,但这似乎是不可能的。最优雅的方法是什么?

4

4 回答 4

64

最终解决方案(减去错误检查),感谢 CommonsWare:

class Worker extends HandlerThread {

    // ...

    public synchronized void waitUntilReady() {
        d_handler = new Handler(getLooper(), d_messageHandler);
    }

}

从主线程:

Worker worker = new Worker();
worker.start();
worker.waitUntilReady(); // <- ADDED
worker.handler.sendMessage(...);

这要归功于HandlerThread.getLooper()在 looper 被初始化之前阻塞的语义。


顺便说一句,这类似于我上面的解决方案#1,因为它HandlerThread的实现大致如下(必须喜欢开源):

public void run() {
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Looper.loop();
}

public Looper getLooper() {
    synchronized (this) {
        while (mLooper == null) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
    }
    return mLooper;
}

关键区别在于它不检查工作线程是否正在运行,而是它实际上创建了一个looper;这样做的方法是将looper存储在一个私有字段中。好的!

于 2011-01-31T20:35:21.283 回答
1

看看源代码HandlerThread

@Override
     public void run() {
         mTid = Process.myTid();
         Looper.prepare();
         synchronized (this) {
             mLooper = Looper.myLooper();
             notifyAll();
         }
         Process.setThreadPriority(mPriority);
         onLooperPrepared();
         Looper.loop();
         mTid = -1;
     }

基本上,如果你在 worker 中扩展 Thread 并实现你自己的 Looper,那么你的主线程类应该扩展 worker 并在那里设置你的处理程序。

于 2015-08-15T22:58:28.833 回答
1

这是我的解决方案: MainActivity:

//Other Code

 mCountDownLatch = new CountDownLatch(1);
        mainApp = this;
        WorkerThread workerThread = new WorkerThread(mCountDownLatch);
        workerThread.start();
        try {
            mCountDownLatch.await();
            Log.i("MsgToWorkerThread", "Worker Thread is up and running. We can send message to it now...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Toast.makeText(this, "Trial run...", Toast.LENGTH_LONG).show();
        Message msg = workerThread.workerThreadHandler.obtainMessage();
        workerThread.workerThreadHandler.sendMessage(msg);

WorkerThread 类:

public class WorkerThread extends Thread{

    public Handler workerThreadHandler;
    CountDownLatch mLatch;

    public WorkerThread(CountDownLatch latch){

        mLatch = latch;
    }


    public void run() {
        Looper.prepare();
        workerThreadHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {

                Log.i("MsgToWorkerThread", "Message received from UI thread...");
                        MainActivity.getMainApp().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.getMainApp().getApplicationContext(), "Message received in worker thread from UI thread", Toast.LENGTH_LONG).show();
                                //Log.i("MsgToWorkerThread", "Message received from UI thread...");
                            }
                        });

            }

        };
        Log.i("MsgToWorkerThread", "Worker thread ready...");
        mLatch.countDown();
        Looper.loop();
    }
}
于 2015-11-24T13:59:14.730 回答
0
    class WorkerThread extends Thread {
            private Exchanger<Void> mStartExchanger = new Exchanger<Void>();
            private Handler mHandler;
            public Handler getHandler() {
                    return mHandler;
            }
            @Override
            public void run() {
                    Looper.prepare();
                    mHandler = new Handler();
                    try {
                            mStartExchanger.exchange(null);
                    } catch (InterruptedException e) {
                            e.printStackTrace();
                    }
                    Looper.loop();
            }

            @Override
            public synchronized void start() {
                    super.start();
                    try {
                            mStartExchanger.exchange(null);
                    } catch (InterruptedException e) {
                            e.printStackTrace();
                    }
            }
    }
于 2015-07-09T13:10:11.833 回答