是否可以从UI线程调用Thread类中的网络方法?

时间:2013-12-17 20:19:14

标签: android multithreading

我很好奇,如果调用的方法是在Threaded类的实例中,是否可以从UI线程调用网络进程...伪...

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();

这对我来说完全违法,但我想知道它是否实际上,如果是这样,为什么?

1 个答案:

答案 0 :(得分:1)

您实际上是在与mnc.doSomeNetworkStuff()相同的线程中调用mnc.start();方法。 这可能是UI线程,但肯定不是刚刚以mnc.start;

开头的线程

考虑一下情况:

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

编辑:

只是为了让事情更清楚。请考虑您有一些静态实用程序类,如下所示:

public static class SomeUtilityClass {

    public static void someUtilityMethod(int i) {
        Log.i("SomeUtilityClass", "someUtilityMethod: " + i);
    }
}

然后在代码中的某个地方,从“主”线程调用:

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);

请注意,Thread#start()会立即退出,并且无法保证您将首先执行对SomeUtilityClass.someUtilityMethod();的哪次调用。