可以code的执行可以通过主事件循环被打断? [英] Can code execution can be interrupted by main event loop?

查看:161
本文介绍了可以code的执行可以通过主事件循环被打断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我说的是一个线程。比如我有它的一个活动的用户界面和下面的方法:

I am talking about one thread. For example I have an Activity ui and following methods in it:

/* TOP LEVEL OF EXECUTION LOOPER NOW WORKING */

class MyActivity extends Activity {
void onCreate(Bundle instance) {
 super.onCreate(instance);
 setContentView(R.layout.activity_main);
 doComplicatedStuff();
}

void doComplicatedStuff() {
 // Doing stuf
}

void onClick() {
 // Process event
}

void anyOtherMethod() {
  /* NOT TOP LEVEL OF EXEUCTION, LOOPER NOW CAN'T WORK */
}
}

/* TOP LEVEL OF EXECUTION, LOOPER NOW WORKING */

所以我的问题是,能doComplicatedStuff()得到的onClick执行()处理器(当然这时,我们有一个点击的按钮)?中断

So my question is, can doComplicatedStuff() be interrupted by execution of onClick() handler (when of course, we had a clicked button) ?

现在我觉得比的onClick()处理程序不能中断doComplicatedStuff()执行,直到doComplicatedStuff()结束其工作。因为code执行顶层,我们有一个活套,接受下一个消息事件并将其分派到处理程序(处理程序,然后调用的onClick()方法)。换句话说,活套做你的工作,只有当没有在这个线程执行的任何方法。

Now I think than onClick() handler can't interrupt doComplicatedStuff() execution until doComplicatedStuff() ends its work. Because on top level of code execution we have an Looper, that accepts next message event and dispatch it to Handler (handler then call onClick() method). In other words, Looper do your work only when there is no any executing method in this thread.

推荐答案

你是正确的。 GUI线程将忙于在OnCreate函数,所以onClick的方法不能叫打断complicatedStuff,即使提交项目到尺蠖。

You're correct. The GUI thread will be busy in the onCreate function, and so the onClick method can't be called to interrupt complicatedStuff, even if submitting an item to the looper.

其实,这样的事情只会当多个线程参与是不可能的。即便如此,如果它需要提交runOnUiThread,它可能会作为一个长期运行的操作过程中出现故障。

In fact, this sort of thing would only be possible if more than one thread were involved. Even then, if it required a submission to runOnUiThread, it would likely fail as a long running operation is in progress.

我建议你在第二个线程执行您的日常complicatedStuff。长期运行的操作不属于在UI线程上。

I suggest you perform your complicatedStuff routine on a second thread. Long running operations do not belong on the UI thread.

这篇关于可以code的执行可以通过主事件循环被打断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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