android in practice_Implementing custom message loops(ProducerConsumer project)
16lz
2021-01-26
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(); }}
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer