I'm curious whether or not it's possible to call a network process from the UI thread if the method called is in an instance of a Threaded class... pseudo...
class MyNetworkClass extends Thread{
public boolean keepGoing = true;
public void run(){
while(keepGoing);
}
public void doSomeNetworkStuff(){
//do things that are illegal on the UI Thread
}
}
//and then in my Activity...
MyNetworkClass mnc = new MyNetworkClass();
mnc.start();
mnc.doSomeNetworkStuff();
This feels totally illegal to me, but I'm wondering if it is in fact, and if so why?
You actually called the mnc.doSomeNetworkStuff()
method from the same thread as mnc.start();
. This is presumably the UI thread, but for sure not the thread which just started with mnc.start
;
Consider the situation:
//creates thread object - does not start a new thread yet
Thread thread = new Thread() {
public void run() {}
};
//...
thread.start(); //this actually started the thread
// the `run` method is now executed in this thread.
//However if you called `run` manually as below
thread.run();
// it would be executed in the thread from which you have called it
// assuming that this flow is running in the UI thread, calling `thread.run()`
// manually as above makes it execute in the UI thread.
EDIT:
Just to make things more clear. Consider that you have some static utility class like below:
public static class SomeUtilityClass {
public static void someUtilityMethod(int i) {
Log.i("SomeUtilityClass", "someUtilityMethod: " + i);
}
}
Then somewhere in your code, called from your "main" thread:
new Thread() {
@Override
public void run() {
// 1.
// call the utility method in new thread
SomeUtilityClass.someUtilityMethod(1);
}
}.start();
// 2.
// call the same method from "main" thread
SomeUtilityClass.someUtilityMethod(2);
Notice that Thread#start()
exits immediately and you are not guaranteed which call to SomeUtilityClass.someUtilityMethod();
will be executed first.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.