异步消息机制源码分析

Android异步消息机制及源码分析 【yian_ http://blog.csdn.net/ 转载烦请注明出处,尊重分享成果】一直对Android中的消息处理机制比较模糊,恰好昨天做了一次Team知识分享,也就借此机会配合源码了解下消息处理机制,仅以博客记录。1 前言一:在分析别人的源码,一直都在workThread配合looper ,handler与uiThread交互互通Message。 二:对于很多初学者老说,大都是知其然而 阅读详情

大家都知道Android中不能再异步线程中更新UI操作。所以异步操作要借用于Handler类。

建Handler类之前必须先Looper.prepare()。然而在主线程可以直接new Handler(),因为APP启动入口是ActivityThread.main函数源码

public static final void main(String[] args) {
SamplingProfilerIntegration.start();

    Process.setArgV0("<pre-initialized>");

    Looper.prepareMainLooper();
    if (sMainThreadHandler == null) {
        sMainThreadHandler = new Handler();
    }


    ActivityThread thread = new ActivityThread();
    thread.attach(false);


    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }


    Looper.loop();


    if (Process.supportsProcesses()) {
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }


    thread.detach();
    String name = (thread.mInitialApplication != null)
        ? thread.mInitialApplication.getPackageName()
        : "<unknown>";
    Slog.i(TAG, "Main thread of " + name + " is now exiting");
}

}

发现主线程/UI线程已经Looper.prepareMainLooper()。

为什么在new Handler()之前为什么要先Loop.prepare(),查看Handler初始化源码

public Handler(Callback callback, boolean async) {
        .......
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
}

再看一下Looper.myLooper()源码

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();   
}


static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

然而sThreadLocal是在Looper.prepare()时加入的。

然后再看一下Looper.prepare()源码

public static void prepare() {
        prepare(true);
}


private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
    throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}

再看一下Looper的构造函数

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
}

发现创建了一个MessageQueue。所以Looper里必绑定一个MessageQueue

所以new Handler之前必须首先Looper.prepare(),主线程已经有了Looper.prepareMainLooper()。

public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
}

所以异步线程创建Handler的时候的伪代码

Looper.prepare();
Handler handler = new Handler();
Looper.Loop();

看一下Looper.Loop()做了什么

public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;


        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();


        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }


            // This must be in a local variable, in case a UI event sets the logger
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }


            msg.target.dispatchMessage(msg);


            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }


            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }


            msg.recycleUnchecked();
        }
}

详细分析一下做了什么

final Looper me = myLooper();

这句是咱们之前Looper.prepare(),创建的looper

final MessageQueue queue = me.mQueue;

这句是Looper.prepare()里sThreadLocal.set调用了Looper的构造函数,构造函数里创建的MessageQueue

for (;;) {}是一个死循环,里面会不断从MessageQueue里取出message交给Handler处理。

Message msg = queue.next(); 查看MessageQueue.next()源码

Message next() {
        ..........
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }


            nativePollOnce(ptr, nextPollTimeoutMillis);


            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }


                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }


                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }


                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }


            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler


                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }


                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }


            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;


            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

先看一下MessageQueue进message

boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }


        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }


            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }


            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

MessageQueue.enqueueMessage()主要做的就是msg进队列。mMessages是队列头部,MessageQueue按照msg.when时间排序插入msg

继续查看MessageQueue.next()源码,发现主要逻辑就是和now时间对比取出头部的msg,然后把mMessages = msg.next,msg.next = null。然后又重新生成队列头部,一直循环取出,不符合条件就进入阻塞。

回过头来再看Looper.loop()函数,分析过messageQueue.next(),下面看一下msg.target.dispatchMessage(msg);

msg.target是什么呢?

回过头再看一下Handler.sendMessage().

public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
}

人后一步步调用会调用到Handler.enqueueMessage()。

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

看到了把msg.target = this = handler

msg.target.dispatchMessage(msg);


public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
 }

msg.callback后面再看,先分析没有callback的,会调用到handlerMessage函数

Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
  };

handlerMessage正好是咱们自己创建handler的回调,在主线程创建的handler,handlerMessage就是在主线程中运行。

msg.callback其实就是在异步线程中运行,下面分析下源码

handler.post(new Runnable() {
            @Override
            public void run() {

            }
});

看一下handler.post源码

public final boolean post(Runnable r){
       return  sendMessageDelayed(getPostMessage(r), 0);
}


private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
}

发现在组装message的时候把runnable指给了message.callback

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
}


private static void handleCallback(Message message) {
        message.callback.run();
}

然后看一下Activity的runOnUiThread

runOnUiThread(new Runnable() {
            @Override
            public void run() {

            }
});

调用到了Activity的

public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
 }

判断如果是主线程,走到了handler.post(runnable),如果是异步的,直接run()方法执行。

最后看一下View.post

btn.post(new Runnable() {
            @Override
            public void run() {

            }
 });
public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }
        // Assume that post will succeed later
        ViewRootImpl.getRunQueue().post(action);
        return true;
}
static final class RunQueue {
        private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();


        void post(Runnable action) {
            postDelayed(action, 0);
        }


        void postDelayed(Runnable action, long delayMillis) {
            HandlerAction handlerAction = new HandlerAction();
            handlerAction.action = action;
            handlerAction.delay = delayMillis;


            synchronized (mActions) {
                mActions.add(handlerAction);
            }
        }


        .....
        void executeActions(Handler handler) {
            synchronized (mActions) {
                final ArrayList<HandlerAction> actions = mActions;
                final int count = actions.size();


                for (int i = 0; i < count; i++) {
                    final HandlerAction handlerAction = actions.get(i);
                    handler.postDelayed(handlerAction.action, handlerAction.delay);
                }


                actions.clear();
            }
        }


        ......
 }

最后会走到handler.postDelayed(handlerAction.action, handlerAction.delay);,handlerAction.action就是view.post(runnable)里的runnable

发现最后又走到了handler.post(runnable)

总结

  1. 已经大概梳理了一下Handler的消息机制,以及post方法和我们常用的sendMessage方法的区别。来总结一下,主要涉及四个类Handler、Message、MessageQueue、Looper:
  2. 新建Handler,通过sendMessage或者post发送消息,Handler调用sendMessageAtTime将Message交给MessageQueue
  3. MessageQueue.enqueueMessage方法将Message以链表的形式放入队列中
  4. Looper的loop方法循环调用MessageQueue.next()取出消息,并且调用Handler的dispatchMessage来处理消息
  5. 在dispatchMessage中,分别判断msg.callback、mCallback也就是post方法或者构造方法传入的不为空就执行他们的回调,如果都为空就执行我们最常用重写的handleMessage
C# WPF上位机实战:从零开发空压机监控系统(含实时监控+故障预警+数据追溯) 在工业生产场景中,空压机作为核心动力设备,常面临这些痛点:压力/温度异常导致停机、油耗超标未及时发现、设备故障追溯无数据支撑、人工巡检效率低且易遗漏。而基于C# WPF开发的空压机监控系统,能通过实时采集设备运行参数、智能分析运行状态、联动故障预警,实现“状态监控-异常告警-数据追溯-远程管控”全流程自动化,完美解决传统管理模式的弊端。今天就带大家落地这套空压机监控系统,基于C# + .NET 8 + WPF + Modbus TCP/RTU协议,整合压力、温度、油耗、运行时长等核心参数监控,搭配WPF的数 阅读详情

相关推荐

别再死记硬背Modbus报文了!用Python+Modbus Poll手把手教你调试工业设备

本文详细介绍了如何利用Python和Modbus Poll工具高效调试工业设备通信。通过实战案例和代码示例,帮助读者快速掌握Modbus通信协议的核心配置、数据监控技巧及Python自动化脚本编写,解决工业设备调试中的常见问题,提升工作效率。

weixin_42520780的博客 344

Android消息机制详细解析

在初学Android的时候我们都碰过这个问题,要从服务端获取数据,这时候,我们知道在主线程不能做耗时操作,否则会引起ANR,更不能在主线程中联网,Android4.0以后会报一异常,或者在子线程中更新UI报出了一个经典异常,我们都知道解决方法是在子线程用Handler发消息给主线程进行更新就可以解决上述两个问题,但是我们会不会疑惑,Handler干了什么事情就可以自由切换线程执行,由于Androi

老实任 2439

从零到一:3D Slicer与MONAI在医学影像中的AI革命

本文探讨了3D Slicer与MONAI在医学影像分析中的革命性应用,展示了如何通过开源工具实现高效的三维影像处理和AI增强分析。结合临床案例,详细介绍了从数据准备到AI分析的全流程,显著提升诊断效率和精度,推动医学影像技术迈向新纪元。

tcp8optimizer的博客 340

LDD3源码分析之异步通知

作者:刘昊昱  博客:http://blog.csdn.net/liuhaoyutz 编译环境:Ubuntu 10.10 内核版本:2.6.32-38-generic-pae LDD3源码路径:examples/scull/pipe.c  examples/scull/main.c   一、异步通知机制的实现 本文分析LDD3第6章中的异步通知机制。 通过使用异步通知机制,应用程

Linux/Android开发记录 2987

wsl2上运行带有Isaac Gym的程序报错: GPU Pipeline: disabled

显示GPU Pipeline:disabled,查找相关文档发现是WSL2目前不支持Isaac Gym,时,想要在wsl2上运行,最后报错如下。

2303_78660611的博客 957

Atlas 300I Pro推理卡性能深度测试:对比业界同类产品的能效比与算力表现

本文对昇腾Atlas 300I Pro推理卡进行了深度性能评测,重点对比了其与业界同类产品的能效比与算力表现。实测数据显示,该卡在运行BERT等模型时展现出高达39.6句子/秒/瓦的卓越能效比,电力成本可降低40%以上,同时其达芬奇架构和硬件加速特征检索能力,为高密度在线推理和向量检索场景提供了强大支撑。

weixin_29031161的博客 578

字符设备驱动(3)——异步通知

#include &lt;linux/module.h&gt; #include &lt;linux/kernel.h&gt; #include &lt;linux/fs.h&gt; #include &lt;linux/init.h&gt; #include &lt;linux/delay.h&gt; #include &lt;linux/irq.h&gt; #include &lt;asm/u...

hfutyyj的博客 231

ESP32使用microPython控制240x240彩色屏幕显示中文

王铭东老师详细讲解了讲了关于240x240屏幕的一些基础东西,我这里在原功能的基础上拓展了中文显示的功能,顺带修改了实际操作过程中程序中遇到的一些问题。

m0_59452630的博客 1万+

【转载】Android异步消息处理机制详解及源码分析

PS一句:最终还是选择优快云来整理发表这几年的知识点,该文章平行迁移到优快云。因为优快云也支持MarkDown语法了,牛逼啊! 【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】 最近相对来说比较闲,加上养病,所以没事干就撸些自己之前的知识点为博客,方便自己也方便别人。 1 背景 之所以选择这个知识点来分析有以下...

aoshu5722的博客 208

半车(前后、左右)、整车悬架详细推导建模和simulink仿真分析

用达朗贝尔定理依据悬架数学模型,得到悬架模型微分方程,分别用simulink建立前后半车、左右半车悬架;结合转向2自由度模型与半车侧倾模型,对模型考虑相干性、延时性的C级随机路面下,仿真分析给定角阶跃输入下的侧倾稳定性。

Mr.邹的博客 1万+

【电机驱动与运动控制】期末重点问题集合

问题1 梯形曲线和S形曲线各自的特点和区别,比较梯形和S形曲线位置、速度、加速度、加加速度的区别。 问题2 总惯量的计算包含哪几个部分? 哪几个部分需要进行折算? 在齿轮箱的输出侧(2号轴)总惯量需要折算到齿轮箱的输入侧(1号轴) 为什么需要折算? 齿轮箱比的存在使2号轴的转速和电机的转速不同 问题3 指出每个部分的名称。 每个部分的功能。 主磁极的励磁绕组:绝大部分直流电机都是由励磁绕组通以直流电建立主磁场; - 电枢铁心:在两个主磁极内表面之间,由硅钢片叠成的圆

【人工智障 | 计算鸡视觉 | 机器孩】 5703

Android异步消息处理机制详解及源码分析

PS一句:最终还是选择优快云来整理发表这几年的知识点,该文章平行迁移到优快云。因为优快云也支持MarkDown语法了,牛逼啊! 【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】 最近相对来说比较闲,加上养病,所以没事干就撸些自己之前的知识点为博客,方便自己也方便别人。 1 背景 之所以选择这个知识点来分析有以下几个原因: 逛G...

kdsde的专栏 278

windows下宝塔安装教程

windows下宝塔安装教程 目录宝塔是什么?宝塔安装流程1.下载2.配置3.登录4.安装的环境套件小结 宝塔是什么? 宝塔是管理服务器的免费的软件,宝塔上面可以进行对你的服务器批量进行管理,对于运维人员来说还是必不可少的一个软件,值得使用。 宝塔安装流程 1.下载 链接: https://download.bt.cn/win/panel/BtSoft.zip 下载后安装买最好自定义目录,方便找 2.配置 下载完成后会出现这个页面,对着页面进行配置 点击默认密码复制进来,这里注意一点就是一定要查看

你在看屏幕的同时,屏幕也在注视着你 4422

Android异步消息处理机制详解及源码分析,android播放音频

SamplingProfilerIntegration.start(); // CloseGuard defaults to true and can be quite spammy. We // disable it here, but selectively enable it later (via // StrictMode) on debug builds, but using DropBox, not logs. CloseGuard.setEnabled(false); Environment

wa32saa的博客 248

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Android异步消息处理机制详解及源码分析(1)

最后小编想说:不论以后选择什么方向发展,目前重要的是把Android方面的技术学好,毕竟其实对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,从来都是我们去适应环境,而不是环境来适应我们!这里附上我整理的几十套腾讯、字节跳动,京东,小米,头条、阿里、美团等公司19年的Android面试题。把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节。由于篇幅有限,这里以图片的形式给大家展示一小部分。

2401_84123201的博客 891

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Android异步消息传递机制源码分析

1、Android异步消息传递机制有以下两个方式:(异步消息传递来解决线程通信问题) handler 和 AsyncTask 2、handler官方解释的用途: 1)、定时任务:通过handler.postDelay(Runnable r, time)来在指定时间执行msg. 2)、线程间通信:在执行较为耗时操作的时候,在子线程中执行耗时任务,然后handler(主线程的)把执行...

A3332221110的博客 140

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Android异步消息处理机制详解及源码分析,android直播sdk

public class MainActivity extends ActionBarActivity { private int mCount = 0; private Handler mHandlerThr = null; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.d(null, “>>&

m0_66264655的博客 1467

Android异步消息处理机制源码分析

声明以下,本文是参考了以下几位大神的文章,自己按照自己的思维习惯整理的笔记,并添加一些相关的内容。 郭霖博客 鸿洋博客 任玉刚《Android开发艺术探索》 一. Andoid消息机制概述 Android规定访问UI只能在主线程进行,如果在子线程中访问UI,那么程序就会抛出异常。ViewRootImpl对UI操作做了验证,这个验证工作是由ViewRootImpl...

ZJXin 341

Handler异步消息处理机制的源码分析

正在编辑中……..1. Handler异步消息处理机制 主线程不能进行耗时操作 (会发生ANR异常) 子线程不能更新UI的操作 (因为会报异常——>只有产生该控件的线程才能操作该控件。) 那么 , 要在子线程请求数据,然后将数据发送到主线程中更新UI , 此时需要使用Handler机制.2. Handler的核心组成部分 Handler : 用于发送消息和处理消息 Message : 用于携带数据

Bloodsoulhacker的博客 458
上一篇: Android构建编译过程
下一篇: HandlerThread源码分析与实战
豪豪6
博客等级 码龄14年 6粉丝 35原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值