Wednesday, April 15, 2015

Performing UI Related task from Worker Thread using Handler

This Example shows How to do UI related task from Worker Thread using Handler. Main Thread contains Handler object. Which ever thread creates Handler object receives message from other thread (Handler Handles the Message).


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

public class Testing extends Activity {

// Handler Basically does Two task 1) Handle Message in current thread 2)
// Send to other Thread for proccessing
Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// UI thread creates object of Handler.  
mHandler = new Handler();

new Thread(new Runnable() { // Worker Thread
// Sending Runnable to Handler MessageQueue which will handled in UI Thread
@Override
public void run() {
mHandler.post(new Runnable() { 
@Override
public void run() {
// Showing Toast Message
Toast.makeText(getApplicationContext(), "I am from Worker Thread", Toast.LENGTH_LONG).show();
}
});
}
}).start();  // Starting Thread
}
}
 

Sending message from one worker thread to other worker thread using Handler and Looper (Android)

Below code snippet explains how to send message from one worker thread to another worker thread using Handler, Looper and Message. First worker thread receive message from second thread.



import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class Testing extends Activity {

//Handler Basically does Two task 1) Handle Message in current thread 2) Send to other Thread for proccessing
Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

new Thread(new Runnable() {   // First worker Thread
@Override
public void run() {
                                // Prepare a Massage Queue for Handler so one by one can be processed
Looper.prepare(); 
mHandler = new Handler() { // Handler is associated with current thread
 // Handling Received Messages
                                       @Override
public void handleMessage(Message msg) {  
super.handleMessage(msg);
System.out.println("Recived By " + Thread.currentThread().getName() + " And Msg is: " + msg.arg1);

}
};
Looper.loop();

}
}).start();

new Thread(new Runnable() {   // Second  Worker Thread
@Override
public void run() {
int i = 0;
while (i < 100) {
/*Obtain a Message from Message Pool. It's good practice not to create Message Object but get from System itself. Saves memory.*/
Message msg = Message.obtain();
System.out.println("Sending MSg via: " + Thread.currentThread().getName() + "Data: " + i);
msg.arg1 += i;
mHandler.sendMessage(msg); // Sending Message to 1st worker thread
i++;
}
}
}).start();
}
}

Tuesday, April 14, 2015

Producer Consumer Problem Using Shared Variable

Hi folks, Below JAVA implementation of Producer Consumer using sheared Variable.Producer Produces and Consumer Consumes.

import java.util.Random;

public class ProducerConsumer {

static int food = 0;
static boolean flag = true; // To ensure producer produces first and for toggle
static Thread producer;
static Thread consumer;

public static void main(String... args) {


// Consumer Thread
consumer = new Thread(new Runnable() {
public void run() {
synchronized (producer) {  // locking producer
while (true) {
if (flag == false) {
try {
Thread.sleep(1000); // Delay so it consumes per second
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I am consuming: "+food);
flag = true;
producer.notify(); // notifying producer
}
}
}
}
});
consumer.start(); // Starting consumer thread

// Producer Thread
producer = new Thread(new Runnable() {
public void run() {
synchronized (consumer) { // locking consumer
while (true) {
if (flag == true) {
try {
Thread.sleep(1000); // Delay so It produces every second
} catch (InterruptedException e) {
e.printStackTrace();
}
food = new Random().nextInt(100); // producing a random number
System.out.println("I am producing: "+food);
flag = false;
consumer.notify(); // Notifying consumer
}
}
}
}
});
producer.start(); // starting Producer Thread

}

}