Runnable在哪个线程上运行? [英] Which thread does Runnable run on?

查看:74
本文介绍了Runnable在哪个线程上运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每100毫秒更新一次UI.在StackOverflow中搜索之后,我找到了使用RunnableHandler这样的解决方案

I want to update UI every 100ms. After searching in StackOverflow, I found a solution using Runnable and Handler like this

final Handler handler = new Handler();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        //update UI here

        handler.postDelayed(this, 100);
    }
};
runnable.run();

有效!但是我有一些问题:

It works! But I have some questions:

  1. Runnable在哪个线程上运行? MainThread还是另一个线程?这是有关postDelay的文档
  1. Which thread does this Runnable run on? MainThread or another thread? Here is the docs about postDelay

Handler已附加MainThread,所以Runnable是否在MainThread上运行?

Handler is attached MainThread, so is Runnable running on MainThread?

  1. 如果Runnable在MainThread上运行,为什么需要Handler?据我了解,Handler用于在两个线程之间发送消息
  1. If Runnable is running on MainThread, why needs Handler? According to my knowledge, Handler is used to send messages between two threads

推荐答案

该Runnable在哪个线程上运行?

Which thread does this Runnable run on?

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        //update UI here

        handler.postDelayed(this, 100);
    }
};
runnable.run()

Runnable在当前线程(即调用此代码的线程)上运行.它不会神奇地创建或构成另一个线程. Runnable.run()仅仅是方法调用.

This Runnable runs on the current thread, i.e. the thread that invokes this code. It doesn't magically create, or constitute, another thread. Runnable.run() is only a method call.

Handler所运行的任何线程中,Handler对该线程的后续执行,除了重新安排自身之外,基本上不执行任何操作.很难相信这可以解决任何问题.

The subsequent executions of this thread, by the Handler, in whatever thread the Handler runs in, do essentially nothing except reschedule themselves. It's hard to believe this is a solution to anything.

这篇关于Runnable在哪个线程上运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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