{{theTime}}

Search This Blog

Total Pageviews

Producer and Consumer Example using LinkedBlockingQueue in Multi Thread Env.

/**
 * Program to Producer the tasks using 100 Threads and 100 Threads Consuming the tasks using LinkedBlockingQueue.

 *   LinkedBlockingQueue Works well in Multi threading env
 *   Orders item in first-in-first-out
 *   Linked Blocking Queue has higher throughput than Array Blocking Queue
 *   add method -- adds the task
 *   take method  -- removes the task 
 * 
 */
import java.util.concurrent.LinkedBlockingQueue;

public class TestLinkedBlockingQueue
{
    
    private static LinkedBlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<String>(1000);
    
    private static class TaskProducer implements Runnable {
        
        String name ;
        public TaskProducer(String s){
            this.name = s;
        }

        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run()
        {
                linkedBlockingQueue.add("Task " + name) ;
                System.out.println("Task added "+ name) ;
        }
    }
    
    private static class TaskConsumer implements Runnable {

        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run()
        {
                String con1;
                try {
                    con1 = linkedBlockingQueue.take();
                    System.out.println("Consumer taken" + con1) ;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } 
        }        
    }
    
    public static void main(String str[]) throws Exception {                
        for(int i= 0; i< 100; i++){            
            TaskProducer taskProducer = new TaskProducer(i+"") ;
            Thread pt = new Thread(taskProducer) ;
            pt.start() ;
            pt.join() ;
        }
        for(int i= 0; i< 100; i++){
            TaskConsumer taskConsumer = new TaskConsumer() ;
            Thread ct = new Thread(taskConsumer) ;
            ct.start() ;
            ct.join() ;
        }
    }
}

No comments:

Generate Insert Sql from Select Statement

SELECT 'INSERT INTO ReferenceTable (ID, Name) VALUES (' +        CAST(ID AS NVARCHAR) + ', ''' + Name + ''...