diff --git a/blogs/Android/Framework/Interview/技巧心得相关/同步处理消息.md b/blogs/Android/Framework/Interview/技巧心得相关/同步处理消息.md new file mode 100644 index 0000000..1dc21f2 --- /dev/null +++ b/blogs/Android/Framework/Interview/技巧心得相关/同步处理消息.md @@ -0,0 +1,59 @@ +--- +怎么同步处理消息? +--- + +```c++ +status_t Client::createSurface(const String&& name, ...){ + sp msg = new MessageCreateLayer(mFlinger.get(), name, this, w, h, format, flags, handle, gbp); + mFlinger->postMessageSync(msg); + return static_cast(msg.get())->getResult(); +} +status_t postMessageSync(const sp& msg, ...){ + mEventQueue.postMessage(msg, reltime); + msg.wait(); +} +class MessageCreateLayer:public MessageBase{ + status_t getResult() const{return result;} + virtual bool handler(){ + result = flinger->createLayer(name, client,w, h, format, ...); + return true; + } +} +``` + +```java +public final boolean runWithScissors(final Runnable r, long timeout){ + if(Looper.myLooper()==mLooper){ + r.run(); + return true; + } + BlockingRunnable br = new BlockingRunnable(r); + return br.postAndWait(this, timeout); +} +private static final class BlockingRunnable implements Runnable{ + public BlockingRunnable(Runnable task){ + mTask = task; + } + + @Override + public void run(){ + mTask.run(); + mDone = true; + notifyAll(); + } +} +public boolean postAndWait(Handler handler, ...){ + if(!handler.post(this)){ + return false; + } + while(!mDone){ + wait(); + } + return true; +} +``` + +#### 总结 + +1. 同步等待消息的处理 +2. Binder 调用统一切换工作线程 \ No newline at end of file