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

            }
        });

    }

}

The picture is about System.out.println

Just like the picture show above: the "anotherThread output: Content=null", I want to Pass information from the main thread to the child thread (in the run method), how can I do it? Try to avoid changing the code of other methods as soon as possible.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • see https://stackoverflow.com/a/25096981/2252830, the second code snippet (after `UPDATE:`) – pskink Oct 21 '18 at 04:04

2 Answers2

0

Given that you want minimal code changes you could use ThreadLocal , value set in Parent threads ThreadLocal is available for all child threads

vinayak
  • 1
  • 1
  • Welcome to SO, your answer may be improved by adding sample code of the suggested solution – Japheth Ongeri - inkalimeva Oct 21 '18 at 09:07
  • The purpose of `ThreadLocal` is so that each thread can have its own copy of something that they all access via the same global "name." That's the opposite of what the OP is asking: The OP is asking how two threads can obtain references to the same shared object. – Solomon Slow Oct 21 '18 at 23:39
0

I think your "otherthread" starts and ends before the data is available in the temp variable, hence it prints null.

You can do something like:

a. Either you start/run your "otherthread" after you fill the temp variable in the handleMessage function.

b. Or if you insist on starting the "otherthread" before you have the data, have the thread in a synchronized way, check the temp variable for being non null after some interval. Also have some sortof boolean to let the thread know, to exit incase you didnt receive any data.

my 2 cents

N0000B
  • 409
  • 1
  • 7
  • 16