1. Child threads and child threads

public class ThreadCommunicationActivity extends Activity { private Button btnGo; private Handler handler; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_thread_communication); btnGo = findViewById(R.id.btn_go); // startChildThread(); btnGo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startChildThread2(); }}); } /** * private void startChildThread() {new Thread(new Runnable() {@override public void run() { Looper.prepare(); // Create Looper handler = new handler () {@override public void handleMessage(MSG) {super.handleMessage(MSG); Log.i("qqq", "====" + msg.obj); }}; Looper.loop(); Looper}}).start(); } private void startChildThread2() {new Thread(new Runnable() {@override public void run() {Message message = Message.obtain(); Message. obj = "Child thread communication succeeded "; handler.sendMessage(message); } }).start(); }}Copy the code

2. Child threads and main threads

public class ThreadCommunicationActivity extends Activity { private Button btnChild; private Handler handlerMain; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_thread_communication); btnChild = findViewById(R.id.btn_child); // final MyThread myThread = new MyThread(); myThread.start(); btnChild.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Message message = new Message(); message.obj="chileThread"; handlerMain.sendMessage(message); }}); } public class MyThread extends Thread {@override public void run() {super.run(); Looper.prepare(); handlerMain = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log. I (" QQQ ", "msg.obj"); }}; Looper.loop(); }}}Copy the code

xml

<? The XML version = "1.0" encoding = "utf-8"? > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/btn_go" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginTop="20dp" android:text="go" /> <Button android:id="@+id/btn_child" android:layout_width="match_parent" android:layout_height="40dp" Android :layout_marginTop="20dp" Android :text=" Send messages to child threads "/> </LinearLayout>Copy the code