1、子线程与子线程
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();//创建Looper
handler = new Handler() {
@Override
public void handleMessage(Message 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 = new Message();
message.obj = "子线程通信成功";
handler.sendMessage(message);
}
}).start();
}
}
2、子线程与主线程
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();
}
}
}
xml
<?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="向子线程发送消息" />
</LinearLayout>
网友评论