一个线程中只有一个Looper,一个MessageQueue。handler可以有多个,然后handler postDelayed(),或者sendMessageDelayed()的时候,那消息队列根据队列的先进先出原则,那其他的Message会不会因此而延迟呢?所以就有了下面的测试:
public class LooperMessageQueueActivity extends AppCompatActivity {
private TextView txt;
private Handler h1;
private Handler h2;
private Handler h3;
private Handler h4;
private Handler h5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_looper_message_queue);
init();
}
private void init() {
txt = (TextView) findViewById(R.id.text);
h1 = new Handler();
h2 = new Handler();
h3 = new Handler();
h4 = new Handler();
h5 = new Handler();
}
public void OnClicked(View view) {
int i = 1;
buildThread(h1, i++);
buildThread(h2, i++);
buildThread(h3, i++);
buildThread(h4, i++);
buildThread(h5, i++);
}
private void buildThread(final Handler h, final int i) {
new Thread(new Runnable() {
@Override
public void run() {
Log.d("Edgar", "t" + i);
h.postDelayed(new Runnable() {
@Override
public void run() {
txt.setText(txt.getText() + "t" + i + "回来啦!\n");
Log.d("Edgar", "t" + i + "回来啦!\n");
}
}, 5000 * (5 - i));
}
}).start();
}
}
然后出来的结果是:
可以看到log出来的时间,是先把后面的显示出来,这与队列的”先进先出”相悖。从结果上看是并发显示出来的。
为什么会出现这个现象呢?这个需要深挖.
由于看不到MessageQueue.enqueueMessage(msg, uptimeMillis)
里面的源码,所以这个日后再分析