Producer and Consumer with Handler

Description

The following code shows how to Producer and Consumer with Handler.

Example

Main Activity Java code


import java.util.Random;
/*w w  w  .  jav  a  2s.com*/
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class MainActivity extends Activity {

   private Handler handler;

   private class Consumer extends Thread {

      @Override
      public void run() {

         Looper.prepare();

         handler = new Handler() {
            @Override
            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();
      }
   }

   private class Producer extends Thread {

      public Producer(String name) {
         super(name);
      }

      @Override
      public void run() {
         Random random = new Random();
         while (true) {
            int number = random.nextInt(100);
            Log.d("Producer " + getName(), Integer.toString(number));
            handler.sendEmptyMessage(number);
            try {
               Thread.sleep(500);
            } catch (InterruptedException e) {
            }
         }
      }
   }

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      new Consumer().start();
      new Producer("A").start();
      new Producer("B").start();
   }
}




















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView