android in practice_Implementing custom message loops(ProducerConsumer project)

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

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

In our simple example, we’ll have two producer threads that generate random numbers and a consumer thread (running a message loop) that receives these 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 consumer
			handler=new Handler(){//bind hanlder to consumer
				public 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 consumer
				try{
					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();
    }
}


你可能感兴趣的:(android in practice_Implementing custom message loops(ProducerConsumer project))