简体   繁体   中英

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

            }
        });

    }

}

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.

考虑到您希望进行最少的代码更改,您可以使用ThreadLocal,在父线程中设置的值ThreadLocal可用于所有子线程

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM