How to implement the main thread waiting for the execution of the sub thread in Android Development

Keywords: Java network

For example, I need to perform network download at a time, when I need to start a thread to perform download, but at a time, I need to use the thread to execute the returned data. At this time, we need the callback mode of the main thread and the while loop mode, so that the main thread can wait for the completion of the sub thread:
eg:
Main thread

 public static String getJson(final String jsonUrl) {
        ThreadForJson threadForJson =new ThreadForJson();
        threadForJson.jsonUrl=jsonUrl;
        threadForJson.start();
       while(threadForJson.flag==false){
           System.out.println("Not ready yet"+flag);
        }
        return threadForJson.result;
    }

Sub thread

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();
        //Time consuming network operations must be done in this seed thread
        URL url = null;
        //Established http link
        HttpURLConnection httpConn = null;
        //Requested input stream
        BufferedReader in = null;

        //Buffer of input stream
        StringBuffer sb = new StringBuffer();

        try {
            url = new URL(jsonUrl);

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

            String str = null;

            //Read in line by line
            while ((str = in.readLine()) != null) {
                sb.append(str);
            }
        } catch (Exception ex) {

        } finally {
            try {
                if (in != null) {
                    in.close(); //Closed flow
                }
            } catch (IOException ex) {

            }
        }
        result = sb.toString();
        callback();
    }
    public  void callback()
    {
        System.out.println("Sub thread execution ended");
        flag=true;
    }

}

Using the callback method to make the main thread wait artificially;

Posted by SteveMellor on Wed, 13 Nov 2019 08:06:16 -0800