你居然叫從同一個線程mnc.start();
的mnc.doSomeNetworkStuff()
方法。 這大概是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();
將首先執行。
你嘗試一下嗎? :) – JanBo
西蒙的評論是不正確的。實際上,你從同一個線程'mnc.start()調用'mnc.doSomeNetworkStuff()','。這大概是UI線程,但肯定不是剛開始使用'mnc.start'的線程。 –
你可以以隱式的方式做到這一點。我建議定義'LinkedBlockingDeque'或類似,則'offer'信號到從UI THEAD隊列,並調用隊列的'poll'在新線程的'run'內無限循環,直到它不被終止。當「輪詢」返回信號時,您執行網絡操作。 – Stan