You’re writing an application in which several threads must exchange messages, as in aproducer-consumer scenario.

We’ve already seen how to bind a handler and use it to send messages. The interestingquestion that remains is how to implement a custom message loop to consume thesemessages outside the UI thread. In Android, message loops for threads are createdusing the Looper class.

In our simple example, we’ll have two producer threads that generaterandom numbers and a consumer thread (running a message loop) that receivesthese numbers and prints a log statement if they’re even.

public class ProducerConsumer extends Activity {private Handler handler;private class Consumer extends Thread{public void run(){Looper.prepare();//create message loop for consumerhandler=new Handler(){//bind hanlder to consumerpublic void handleMessage(Message msg){int number=msg.what;if(number%2==0){  Log.d("Consumer", number + " is divisible by 2");}else{Log.d("Consumer", number + " is not divisible by 2");}}};Looper.loop();//run message loop}}private class Producer extends Thread{public Producer(String name){super(name);}public void run(){Random random=new Random();while(true){int number=random.nextInt(100);Log.d("Producer " + getName(), Integer.toString(number));handler.sendEmptyMessage(number);//send number to consumertry{Thread.sleep(500);}catch(InterruptedException e){}}}}    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        new Consumer().start();        new Producer("A").start();        new Producer("B").start();    }}


更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. android 安全讲座第四层(扩展篇)
  2. Android(安卓)+ HTML开发手机应用 demo
  3. android 仿IOS实现SegmentControl
  4. android中非阻塞socket通信
  5. Android(安卓)Beam 告诉我们未来近距离数
  6. android 下使用GPS 无法获取经纬度的解决
  7. 说说在 Android(安卓)中如何接收系统广播
  8. Android:四大组件之-----广播(Broadcast)
  9. Android子菜单和选项菜单与上下文菜单的
  10. android listview或者ScrollView 去除顶