安卓开发中如何实现主线程等待子线程执行

比如,我需要在a时间执行网络下载,这个时候是需要开启一个线程执行下载,但是在a我又需要用线程执行完,返回的数据,这个时候我们需要主线程的callback方式,用while循环的方式,使得主线程能够等待子线程完成:
eg:
主线程中

 public static String getJson(final String jsonUrl) {
        ThreadForJson threadForJson =new ThreadForJson();
        threadForJson.jsonUrl=jsonUrl;
        threadForJson.start();
       while(threadForJson.flag==false){
           System.out.println("还没准备好"+flag);
        }
        return threadForJson.result;
    }

子线程

package com.baihe.newsconsult.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by
 * Project_Name: NewsConsult
 * Package_Name: com.baihe.newsconsult.util
 * Date: 2019/5/9
 * Time: 20:30
 */
public class ThreadForJson extends Thread {
    boolean flag=false;
    String jsonUrl;
    String result;
    public ThreadForJson(){
        System.out.println("this is ThreadForJson contruct methud!");

    }
    @Override
    public void run() {
        System.out.println("this is ThreadForJson RUN");
        super.run();
        //耗时的网络操作必须要在这种子线程里面去做
        URL url = null;
        //建立的http链接
        HttpURLConnection httpConn = null;
        //请求的输入流
        BufferedReader in = null;

        //输入流的缓冲
        StringBuffer sb = new StringBuffer();

        try {
            url = new URL(jsonUrl);

            in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

            String str = null;

            //一行一行进行读入
            while ((str = in.readLine()) != null) {
                sb.append(str);
            }
        } catch (Exception ex) {

        } finally {
            try {
                if (in != null) {
                    in.close(); //关闭流
                }
            } catch (IOException ex) {

            }
        }
        result = sb.toString();
        callback();
    }
    public  void callback()
    {
        System.out.println("子线程执行结束");
        flag=true;
    }

}

利用callback方法来人为的让主线程等待;

猜你喜欢

转载自blog.csdn.net/crh170/article/details/90060811