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