java - new Runnable() 但没有新线程?

标签 java android multithreading runnable

我正在尝试理解代码 here ,特别是匿名类

private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
   final long start = mStartTime;
   long millis = SystemClock.uptimeMillis() - start;
   int seconds = (int) (millis / 1000);
   int minutes = seconds / 60;
   seconds     = seconds % 60;

   if (seconds < 10) {
       mTimeLabel.setText("" + minutes + ":0" + seconds);
   } else {
       mTimeLabel.setText("" + minutes + ":" + seconds);            
   }

   mHandler.postAtTime(this,
           start + (((minutes * 60) + seconds + 1) * 1000));
   }
};

文章说

The Handler runs the update code as a part of your main thread, avoiding the overhead of a second thread..

不应该创建一个新的 Runnable 类来创建一个新的第二个线程吗?除了能够将 Runnable 类传递给 postAtTime 之外,这里 Runnable 类的目的是什么?

谢谢

最佳答案

Runnable 常用于提供线程应该运行的代码,而Runnable 本身与线程无关。它只是一个带有 run() 方法的对象。

在 Android 中,Handler 类可用于要求框架稍后在 相同 线程上运行一些代码,而不是在另一个线程上运行。 Runnable 用于提供稍后应该运行的代码。

关于java - new Runnable() 但没有新线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9029795/

相关文章:

java - Play 2.5.3 : Using dependency injection to get configuration values

javax.net.ssl.SSLException : Read error: ssl=0x56e63588: I/O error during system call, 连接被对等重置

android - 将您自己的项目 Hook 到 "share-list"

java - Gradle console() 为空,守护进程被禁用

java - Struts2 - append标签生成的结果不能迭代多次

java - 如何用 Java 为该 WS 创建 SOAP 请求信封?

java - 为什么会出现这个错误我什至还没有开始编码

ios - 在后台 Context 上保存 NSManagedObject 时出现问题

java - 服务中的多线程 (Android/Java)

java - 重绘在线程中不起作用