Bulk Emailing

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Wednesday, 7 July 2010

Few Multi-Threading Implementations

Posted on 01:25 by Unknown

Sequential Producer & Consumer
In my first example, I will demonstrate an implementation to solve the famous producer and consumer problem. Producer should complete its production, before Consumer can consume it, as simple as that. In addition, both the operations should run on 2 separate threads.
public class SequentialExecutor {

      /**
       * Shared
       */
      volatile int shared;
     
      /**
       * Lock object, whose monitor will be shared by both the threads
       */
      Object lock = new Object();
     
      /**
       * Producer
       */
      P p;
     
      /**
       * Consumer
       */
      C c;
     
      public SequentialExecutor(){
            p = new P();
            c = new C();
      }
     
      public class P implements Runnable {
            public void run(){
                  while(true){
                        synchronized (lock) {
                              try{
                                    // add some processing delay
                                    Thread.sleep(1000);
                              }catch(Exception ex){
                                    ex.printStackTrace();
                              }
                              shared++;
                              System.out.println("Produce->"+ shared);
                        }
                  }
            }
      }
     
      public class C implements Runnable {
            public void run(){
                  while(true){
                        synchronized (lock) {
                              try{
                                    // add some processing delay
                                    Thread.sleep(1500);
                              }catch(Exception ex){
                                    ex.printStackTrace();
                              }
                              System.out.println("Consume->"+ shared);
                        }
                  }
            }
      }
     
      public static void main(String[] args){
            SequentialExecutor se = new SequentialExecutor();
            new Thread(se.p, "P Thread").start();
            new Thread(se.c, "C Thread").start();
      }
}
You’ll get output as-
Produce->1
Consume->1
Produce->2
Consume->2
Produce->3
Consume->3
Produce->4
Consume->4
Here the trick is being done by the common object lock.

Binary Semaphore Implementation
public class Semaphore {

      int counter = 0;
      /**
       * Binary Semaphore- restricts the probable counter values
       * to (0/1)
       */
      int BOUND = 1;
     
      /**
       * Acquire the lock.
       * This SHOULD be an Atomic operation
       */
      public synchronized void acquire(){
            Thread currentThread = Thread.currentThread();
            System.out.println("[acquire] Thread: "+ currentThread.getName()+" - Start");
            System.out.println("Counter: "+ counter);
           
            while(counter == BOUND){
                  // make the calling  thread wait
                  System.out.println(currentThread.getName()+ " Waiting to Acquire...");
                  try{
                        wait();
                  }catch(Exception ex){
                        ex.printStackTrace();
                  }
            }
            counter++;
            System.out.println("[acquire] Thread: "+ currentThread.getName()+" -Done");
      }
     
      /**
       * Release the lock.
       * This SHOULD be an Atomic operation
       */
      public synchronized void release(){
            Thread currentThread = Thread.currentThread();
            System.out.println("[release] Thread: "+ currentThread.getName());
            System.out.println("Counter: "+ counter);
           
            if(counter > 0){
                  counter--;
                  try{
                        // Notify the other thread waiting to acquire lock
                        notify();
                  }catch(Exception ex){
                        ex.printStackTrace();
                  }
            }
      }
}
How to use it-
  1. Acquire the Semaphore lock- acquire()

  2. Do some operation.

  3. Release the Semaphore lock. (Make sure you release it. Otherwise, other threads will never get chance to execute)- release()


Email ThisBlogThis!Share to XShare to Facebook
Posted in | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Weekend at Yeouido (Han River Cruise)
    Yeouido is one of the Han River Cruise boarding points. It has a wonderful river side park (Yeouido P...
  • CityWeather
    Update: Release 1.1 has been uploaded. It will now provide weekly forecast of your selected cities. Download   CityWeather is an Android...
  • Few Multi-Threading Implementations
    Sequential Producer & Consumer In my first example, I will demonstrate an implementation to solve ...
  • Accessing Yahoo Finance API
    Since last few days I was wondering the right set of Web Service to read Country wise Stock Exchange index information . I found a bunch of ...
  • Regular Expression in JavaScript
    I was struggling to get familiar with JavaScript's Regular expression handling and thought my learning might help others. Here I'll...
  • Alphanumeric Random Number
    Sometime basic things becomes tricky :-) Was trying to find out ways to generate some alphanumeric random number whose size (i.e. number of ...
  • Binary Search Tree in Java
    This post is a part of my continuous effort to just implement few of the important data structures in ...
  • QuickSort in Java
    This post is a part of my continuous effort to just implement few of the important data structures in Java. Please find my previous post on ...
  • InDroid- Access to Android's Hidden API
    I have started one project " InDroid " to expose and share Hidden and Internal methods and variables of Android platform which are...
  • Image Geo Tagging for Android
    " onMap " is an Image Geo Tagging application, which can read EXIF header of images stored in your Android device and Map them ov...

Blog Archive

  • ►  2013 (6)
    • ►  September (2)
    • ►  May (1)
    • ►  April (1)
    • ►  February (1)
    • ►  January (1)
  • ►  2012 (4)
    • ►  July (2)
    • ►  March (1)
    • ►  January (1)
  • ►  2011 (11)
    • ►  November (1)
    • ►  October (2)
    • ►  August (1)
    • ►  June (1)
    • ►  April (2)
    • ►  March (3)
    • ►  January (1)
  • ▼  2010 (27)
    • ►  December (2)
    • ►  November (3)
    • ►  September (2)
    • ►  August (4)
    • ▼  July (4)
      • Custom Logger for Android
      • Weekend at Yeouido (Han River Cruise)
      • A day at Suwon World Cup Stadium
      • Few Multi-Threading Implementations
    • ►  June (7)
    • ►  May (5)
Powered by Blogger.

About Me

Unknown
View my complete profile