任何人都可以解释一下,runOnUiThread
会创建新线程吗?或者它将适用于当前线程
someActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
答案 0 :(得分:5)
不,它不会创建任何新线程。您指定的操作将在应用程序的UI线程上运行。您可以从其他线程(后台线程)发布操作以在UI线程上运行。 (比如更新您必须在UI线程上执行的视图等)。
https://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
答案 1 :(得分:1)
您的UI-Thread始终在运行。此方法只在您现有的UI-Thread上运行。因此,不会创建任何线程。
答案 2 :(得分:0)
我使用sleep函数测试它,日志显示它是同一个线程。
coalesce1a <- function(...) {
ans <- ..1
for (elt in list(...)[-1]) {
i <- which(is.na(ans))
ans[i] <- elt[i]
}
ans
}
setDT(d1)
setDT(d2)
#melt into long formats and full outer join the 2
mdt <- merge(melt(d1, id.vars="id"), melt(d2, id.vars="id"), by=c("id","variable"), all=TRUE)
#perform a coalesce on vectors
mdt[, value := do.call(coalesce1a, .SD), .SDcols=grep("value", names(mdt), value=TRUE)]
#pivot into original format and subset to those in d1
dcast.data.table(mdt, id ~ variable, value.var="value")[
d1, .SD, on=.(id)]
线程中的Toast使用runOnUiThread:
05-31 08:47:06.481 6538-6538/com.example.languoguang.welcomeapp I/MainActivity: onPause:
05-31 08:47:07.888 6538-6538/com.example.languoguang.welcomeapp I/MainActivity: onStop:
05-31 08:47:07.893 6538-6538/com.example.languoguang.welcomeapp I/MainActivity: onDestroy:
05-31 08:47:10.294 6538-6538/com.example.languoguang.welcomeapp I/MainActivity: run: in
05-31 08:47:25.315 6538-6538/com.example.languoguang.welcomeapp I/MainActivity: run: out
05-31 08:47:25.362 6538-6538/com.example.languoguang.welcomeapp I/MainActivity: onStart:
05-31 08:47:25.366 6538-6538/com.example.languoguang.welcomeapp I/MainActivity: onResume:
添加,runOnUiThread签名:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = $(R.id.main_text);
if (textView != null) {
textView.setOnClickListener(this);
}
initializeStartButton();
initializeSetButton();
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Log.i(TAG, "run: in");
Thread.sleep(15000);
Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
Log.i(TAG, "run: out");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
Log.e(MainActivity.TAG, "onCreate: ", e);
}
}