线程和处理程序之间的区别 [英] difference between Thread and Handler

查看:110
本文介绍了线程和处理程序之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我Thread和Handler之间的区别吗?什么时候使用Thread和何时使用Handler?

Can somebody tell me the deference between Thread and Handler? When we use Thread and when we use Handler?

我的项目中有两个代码,但是我听不懂.

I have two code in my project , But I can't understand them.

final Handler handler =  new Handler()
{
    @Override
    public void handleMessage(Message msg)
    {
        //  Do SomeThings
    } 
};

还有

private class readThread extends Thread
{
    Handler mHandler;

    readThread(Handler h){
        mHandler = h;
        this.setPriority(Thread.MIN_PRIORITY);

    }

    @Override
    public void run()
    {
        //  Do SomeThings
    }
}

然后在另一个方法中调用这样的处理程序

And in another method call the handler like this

read_thread = new readThread(handler);
            read_thread.start();

哪个首先运行?有人可以解释一下我吗?

Which one run first?? Can somebody explain me?

推荐答案

相同:两者都可以异步执行任务而不会阻塞当前代码,

The same: you can both execute task asynchronously without blocking your current code,

差异:假设您有一个Runnable r = new Runnable{...}

  • 使用new Thread(r).start()时,实际上创建了一个新线程并异步运行任务.

  • When you use new Thread(r).start(), you actually created a new thread and run task asynchronously.

使用new Handler().post(r)(或Message)时,已将Runnable对象添加到Looper,并稍后在同一线程中执行代码.

When you use new Handler().post(r) (or Message), you added the Runnable object to Looper and execute the code later in the same thread.

A Thread,通常为MainThreadUIThread包含Looper. MainThread运行时,它将循环Looper并逐个执行Runnable.

A Thread, generally MainThread or UIThread contains a Looper. When MainThread runs, it will loop the Looper and execute Runnable one by one.

首选线程"时:

当您要进行繁重的工作(如网络通信或解码大型位图文件)时,最好使用新线程.如果需要大量线程,则可能更优选ExecutorService. https://developer.android.com/reference/java/util/concurrent /ExecutorService.html

When you're doing a heavy work like network communication, or decoding large bitmap files, a new thread is preferred. If a lot of thread is needed, maybe ExecutorService is preferred further. https://developer.android.com/reference/java/util/concurrent/ExecutorService.html

首选使用处理程序时:

当您想从其他线程更新UI对象(如TextView文本)时,有必要只能在UI Thread中更新UI对象. 另外,当您只想稍后运行一些轻量代码(例如300ms的延迟)时,可以使用Handler,因为它更轻,更快.

When you want to update UI objects (like TextView text) from other thread, it is necessary that UI objects could only be updated in UI Thread. Also, when you just want to run some light code later (like the delay for 300ms) you can use Handler because it's lighter and faster.

另请参阅处理程序与AsyncTask与线程

这篇关于线程和处理程序之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆