Android非UI主线程中,若干普通Java线程使用Handler发送接收消息

Android非UI主线程中,若干普通Java线程使用Handler发送接收消息


线程1和线程2均为普通Java线程,在Android中创建,然后在这两个普通Java线程中使用Handler发送和接收消息。

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    private final String TAG = "输出";
    private final int WHAT = 0xa01;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "Android主线程id:" + Thread.currentThread().getId());

        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "线程1的id:" + Thread.currentThread().getId());

                Looper.prepare();
                handler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        if (msg.what == WHAT) {
                            Log.d(TAG, msg.obj + "@" + System.currentTimeMillis());
                            handler.removeMessages(WHAT);
                        }
                    }
                };
                Looper.loop();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "线程2的id:" + Thread.currentThread().getId());

                while (true) {
                    if (handler != null) {
                        Message msg = handler.obtainMessage();
                        msg.what = WHAT;
                        msg.obj = Thread.currentThread().getId() + "";
                        handler.sendMessage(msg);

                        SystemClock.sleep(1000);
                    }
                }
            }
        }).start();
    }
}



输出:

02-09 09:39:01.029 12544-12544/com.example.fly.myapplication D/输出: Android主线程id:1
02-09 09:39:01.030 12544-12628/com.example.fly.myapplication D/输出: 线程1的id:12146
02-09 09:39:01.032 12544-12629/com.example.fly.myapplication D/输出: 线程2的id:12147
02-09 09:39:01.033 12544-12628/com.example.fly.myapplication D/输出: 12147@1518140341033
02-09 09:39:02.033 12544-12628/com.example.fly.myapplication D/输出: 12147@1518140342033
02-09 09:39:03.033 12544-12628/com.example.fly.myapplication D/输出: 12147@1518140343033
02-09 09:39:04.034 12544-12628/com.example.fly.myapplication D/输出: 12147@1518140344034
......


附:

1,《Android Handler,Looper,Message》链接:http://blog.csdn.net/zhangphil/article/details/43878993

上一篇:迈伴客金融荣获“2016优秀互联网金融服务商”大奖


下一篇:libevent 接收TCP连接