Can code execution can be interrupted by main even

2019-09-04 18:38发布

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条回答
Emotional °昔
2楼-- · 2019-09-04 19:29

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.

查看更多
登录 后发表回答