我正在尝试理解代码 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/