简体   繁体   English

主线程如何将信息传输到子线程(如何在run方法中处理消息?)?

[英]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 图片是关于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? 就像上面的图片一样:“ anotherThread输出:Content = null”,我想将信息从主线程传递到子线程(在run方法中),该怎么办? 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. 我认为您的“ otherthread”在temp变量中的数据可用之前开始和结束,因此它显示null。

You can do something like: 您可以执行以下操作:

a. 一种。 Either you start/run your "otherthread" after you fill the temp variable in the handleMessage function. 在handleMessage函数中填充temp变量后,您可以启动/运行“ otherthread”。

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. 或者,如果您坚持要在拥有数据之前启动“ otherthread”,请以同步方式使线程运行,请在一定间隔后检查temp变量是否为非null。 Also have some sortof boolean to let the thread know, to exit incase you didnt receive any data. 还有一些sortof布尔值让线程知道,以防万一您没有收到任何数据而退出。

my 2 cents 我的2美分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Java应用程序中从Main方法运行线程? - How can I run thread from Main method in Java application? 主方法关闭后如何运行线程? - How can thread run after main method closes? 线程类的start()方法在实现线程类时如何调用子类的run()方法 - how does start() method of thread class call run() method of child class when it implements thread class Java中的子线程如何向主线程(方法)发送连续消息? - How can a child thread send continuous messages to main thread(method) in Java? 当离开主线程时,如何才能使一些代码尽快在主线程上运行? - When off the main thread, how can I get some code to run on the main thread as quickly as possible? 如何使用从另一个线程收到的信息更新主UI? (虽然线程仍在运行) - How can I update the Main UI with information received from another thread? (While the thread is still running) 如何将主线程作为实时线程运行 - How to run main thread as a real time thread Java中如何将子线程的消息返回到主线程(方法)? - How to return messages from child threads to main thread(method) in Java? 如何在“主”线程上运行DefaultMessageListenerContainer - How to run DefaultMessageListenerContainer on the 'main' thread 如何从线程中调用与run()不同的方法 - How can I call a different method than run() from a Thread
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM