Can code execution can be interrupted by main event loop?

情到浓时终转凉″ 提交于 2019-12-12 05:24:27

问题


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 */

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

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.


回答1:


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.

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.

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



来源:https://stackoverflow.com/questions/17499435/can-code-execution-can-be-interrupted-by-main-event-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!