zoukankan      html  css  js  c++  java
  • Handler向子线程发送数据

    public class MainActivity extends AppCompatActivity {
        private static final String TAG = "MainActivity";
    private Button btn = null;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            btn =  findViewById(R.id.btn);
            HandlerThread t1 = new  HandlerThread();
            HandlerThread t2 = new HandlerThread();
    
            t1.start();
            t2.start();
            try {
                /**
                 *   等待  使子线程内的handler能够初始化完毕,避免 时序错误带来的 mHandler = null
                 */
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
            }
    
            t1.mHandler.sendMessage(new Message());
            t2.mHandler.sendMessage(new Message());
    //        t1.stop();
    //        t2.stop();
        }
    
        static  public class HandlerThread extends  Thread{
           public Handler  mHandler;
            @Override
            public void run() {
                Looper.prepare(); // 子线程无默认的 looper 需手动添加  
                mHandler = new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        Log.d(TAG, "handleMessage:---------------------------- "+Thread.currentThread().getName());
                        Log.d(TAG, "Thread ID-----------------------"+Thread.currentThread().getId());
                    }} ;
                Looper.loop(); // 循环
            };
            }
        }

    日志输出:

    2018-11-08 14:09:44.411 6000-6022/com.example.admin.handlertest D/MainActivity: handleMessage:---------------------------- Thread-2
    2018-11-08 14:09:44.411 6000-6023/com.example.admin.handlertest D/MainActivity: handleMessage:---------------------------- Thread-3
    2018-11-08 14:09:44.411 6000-6023/com.example.admin.handlertest D/MainActivity: Thread ID-----------------------43152
    2018-11-08 14:09:44.411 6000-6022/com.example.admin.handlertest D/MainActivity: Thread ID-----------------------43151
  • 相关阅读:
    freemarker 遍历 hashmap 到select option
    三分钟跑起jsblocks
    hibernate_@GeneratedValue
    跑github上的Symfony项目遇到的问题2
    Activiti使用过程_1
    Symfony官方视频教程
    跑github上的Symfony项目遇到的问题
    剧本杀
    随遇而安
    开发者职场心得
  • 原文地址:https://www.cnblogs.com/the-wang/p/9928911.html
Copyright © 2011-2022 走看看