[英]How does the main thread transmit information to the child thread (How can I handle message in the run method?)?
public class MainActivity extends AppCompatActivity {
public static final int TRANSMIT_DATA = 1;
public static String string0;
public String temp;//定義全局變量,想要把string0的值傳給它。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadData();
System.out.println("Main output:ID="+Thread.currentThread().getId());
anotherThread();
}
public void anotherThread(){
new Thread(){
public void run() {
System.out.println("anotherThread :ID="+Thread.currentThread().getId());
System.out.println("anotherThread output: Content="+temp);
}
}.start(); //開啟一個線程
}
private Handler dataHandler =new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case TRANSMIT_DATA:
System.out.println("handleMessage output:ID="+Thread.currentThread().getId());
System.out.println("handleMessage output: Content="+msg.obj);
temp=msg.obj.toString();
break;
default:
break;
}
}
};
public void loadData() {
OkHttpClient okHttpClient = new OkHttpClient();
//構造Request,
//builder.get()代表的是get請求,url方法里面放的參數是一個網絡地址
Request.Builder builder = new Request.Builder();
final Map params = new LinkedHashMap();// 請求參數
Request request = builder.get()
.url("https://api.avatardata.cn/Jztk/Query?key=15f9ceafeeb94a2492fd84b8c68a554c&subject=4&model=c1&testType=rand")
.build();
//3將Request封裝成call
Call call = okHttpClient.newCall(request);
//4,執行call,這個方法是異步請求數據
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//失敗調用
Log.e("MainActivity", "onFailure: " );
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
//成功調用
Log.e("MainActivity", "onResponse: " );
//獲取網絡訪問返回的字符串
string0 = response.body().string();
System.out.println("Asynchronous Request Output:ID="+Thread.currentThread().getId());
Message message = new Message();
message.obj = string0;
message.what =TRANSMIT_DATA;
dataHandler.sendMessage(message);
}
});
}
}
就像上面的圖片一樣:“ anotherThread輸出:Content = null”,我想將信息從主線程傳遞到子線程(在run方法中),該怎么辦? 嘗試避免盡快更改其他方法的代碼。
考慮到您希望進行最少的代碼更改,您可以使用ThreadLocal,在父線程中設置的值ThreadLocal可用於所有子線程
我認為您的“ otherthread”在temp變量中的數據可用之前開始和結束,因此它顯示null。
您可以執行以下操作:
一種。 在handleMessage函數中填充temp變量后,您可以啟動/運行“ otherthread”。
灣 或者,如果您堅持要在擁有數據之前啟動“ otherthread”,請以同步方式使線程運行,請在一定間隔后檢查temp變量是否為非null。 還有一些sortof布爾值讓線程知道,以防萬一您沒有收到任何數據而退出。
我的2美分
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.