Shared queue processing with Pub and Sub Threads

import java.util.Random;

public class PubSubDemo {

	public static void main(String[] args) {
		SharedQ sharedQ = new SharedQ();

		new Thread(new Consumer(sharedQ), "Consumer").start();
		// Delay publishing
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		new Thread(new Producer(sharedQ), "Producer").start();
	}

}

class Producer implements Runnable {
	SharedQ sharedQPro = null;

	public Producer(SharedQ sharedQ) {
		this.sharedQPro = sharedQ;
	}

	@Override
	public void run() {
		for (int i = 0; i < 3; i++) {
			produce();
		}
	}

	public void produce() {
		synchronized (sharedQPro.sharedQueue) {

			for (int i = 0; i < 3; i++) {
				sharedQPro.sharedQueue[i] = (new Random().nextInt(20));
				System.out.println(" ### Produced ### " + sharedQPro.sharedQueue[i]);
			}
			sharedQPro.sharedQueueIsEmpty = false;
			sharedQPro.sharedQueue.notify();
			try {
				sharedQPro.sharedQueue.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

class Consumer implements Runnable {
	SharedQ sharedQCon = null;

	public Consumer(SharedQ sharedQ) {
		this.sharedQCon = sharedQ;
	}

	@Override
	public void run() {
		for (int i = 0; i < 3; i++) {
			consume();
		}
	}

	public void consume() {
		synchronized (sharedQCon.sharedQueue) {
			if (sharedQCon.sharedQueueIsEmpty) {
				try {
					sharedQCon.sharedQueue.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			System.out.println();

			for (int i = 0; i < 3; i++) {
				System.out.println(" *** Consumed *** " + sharedQCon.sharedQueue[i]);
				sharedQCon.sharedQueue[i] = 0;
			}
			sharedQCon.sharedQueue.notify();
			System.out.println(" --------------------------");
			try {
				sharedQCon.sharedQueue.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

}

class SharedQ {

	int[] sharedQueue = new int[3];
	boolean sharedQueueIsEmpty = true;

}

/*
Output of pub sub :

 ### Produced ### 1
 ### Produced ### 0
 ### Produced ### 3

 *** Consumed *** 1
 *** Consumed *** 0
 *** Consumed *** 3
 --------------------------
 ### Produced ### 12
 ### Produced ### 0
 ### Produced ### 14

 *** Consumed *** 12
 *** Consumed *** 0
 *** Consumed *** 14
 --------------------------
 ### Produced ### 13
 ### Produced ### 8
 ### Produced ### 17

 *** Consumed *** 13
 *** Consumed *** 8
 *** Consumed *** 17
 --------------------------
*/

Sequence generator tasks by Threads

Many times we face scenario where we need to execute two sequential tasks to perform a operation, like Tagging / Stamping serial Coupons , Producing serial Tickets at different Vending Machines. Below code ( generating Odd and Even in sequence) can be used for such requirement.

PS: This is a basic implementation, the same can be done using other Threading concepts.

				
package multithreading;

// print ODD and Even number alternatively

public class SquenceGeneratorTasks {

	public static boolean oddPrinted = false;

	public static void main(String[] args) {
		 Object lock =new Object();
		Thread oddThread = new Thread(new Runnable() {

			@Override
			public void run() {
				int i = 1;
				while (i <= 20) {

					synchronized (lock) {
						if (!oddPrinted) { // make sure printing starting with Odd number and each Odd is followed with a Even number
							System.out.println(i);
							i = i + 2;
							oddPrinted = true;
							lock.notify();
							try {
								lock.wait();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}

				}
			}
		});

		
		Thread evenThread = new Thread(new Runnable() {

			@Override
			public void run() {
				
				System.out.println(" Though you have delayed Odd thread but printing gonna start with Odd number only !!");
				
				int i = 2;
				while (i <= 20) {
					synchronized (lock) {
						if (oddPrinted) {
							System.out.println(i);
							i = i + 2;
							oddPrinted = false;
							lock.notify();
							try {
								lock.wait();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}
			}
		});

		evenThread.start();
		
		// even if We apply some delay to Odd thread printing will start with ODD number only and 
		// Sequence of Odd-Even-Odd maintained
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		oddThread.start();

	}

}						
/*
Though you have delayed Odd thread but printing gonna start with Odd number only !!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 */

You can download the same code from : https://github.com/SkilledMinds/easyNuts/tree/master/code-25-09-2015

Sample code for Producer n Consumer Problem

There are at least 5 direct ways to write a Producer n Consumer Problem. The basic is one which use wait() and notify().

// Queue
class CustomerQueue
{

    String sharedCustomerQueue[] = new String[5];
}

// Client
public class ProducerConsumerQ
{

    static int NEED_TO_SERVE_BATCH = 2;

    public static void main(String[] args)
    {

        System.out.println(" Producer will fill SharedQueue with 5 elements in each batch.");
        System.out.println(" Consumer will consume elements available in SharedQueue in each batch.");

        System.out.println(" Total " + NEED_TO_SERVE_BATCH + " will be served.");
        System.out.println(" \n ***************************************************************************** ");
        CustomerQueue cq = new CustomerQueue();
        Thread pro = new producer(cq);
        Thread con = new consumer(cq);
        pro.setName("Producer");
        con.setName("Consumer");
        pro.start();
        con.start();

    }

}

class producer extends Thread
{

    int count = 0;
    CustomerQueue qp;

    public producer(CustomerQueue q)
    {
        qp = q;
    }

    @Override
    public void run()
    {

        while (count < ProducerConsumerQ.NEED_TO_SERVE_BATCH)
        {
            System.out.println("\n");
            synchronized (qp.sharedCustomerQueue)
            {

                // everytime generate 5 random numbers and put in Queue
                for (int p = 0; p < 5; p++)
                {
                    qp.sharedCustomerQueue[p] = (int) ((Math.random() * 10) % 10) + "";
                    System.out.println("Producer : Genereated item is :" + qp.sharedCustomerQueue[p]);
                }
                qp.sharedCustomerQueue.notify();
                try
                {
                    qp.sharedCustomerQueue.wait();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                count++;
            }
        }

    }
}

class consumer extends Thread
{

    int count = 0;
    CustomerQueue qc;

    public consumer(CustomerQueue q)
    {
        qc = q;
    }

    @Override
    public void run()
    {

        while (count < ProducerConsumerQ.NEED_TO_SERVE_BATCH)
        {
            if (qc.sharedCustomerQueue[0] != null) // consume only if queue is filled
            {
                synchronized (qc.sharedCustomerQueue)
                {

                    for (String qItem : qc.sharedCustomerQueue)
                    {
                        System.out.println("Consumer : Consuming item " + qItem);
                    }

                    System.out.println("\n");
                    qc.sharedCustomerQueue.notify();

                    try
                    {
                        qc.sharedCustomerQueue.wait();
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        }

    }
}

/*
 Producer will fill SharedQueue with 5 elements in each batch.
 Consumer will consume elements available in SharedQueue in each batch.
 Total 2 will be served.
 
 ***************************************************************************** 
Producer : Genereated item is :3
Producer : Genereated item is :5
Producer : Genereated item is :5
Producer : Genereated item is :1
Producer : Genereated item is :1
Consumer : Consuming item 3
Consumer : Consuming item 5
Consumer : Consuming item 5
Consumer : Consuming item 1
Consumer : Consuming item 1




Producer : Genereated item is :9
Producer : Genereated item is :5
Producer : Genereated item is :8
Producer : Genereated item is :9
Producer : Genereated item is :8
Consumer : Consuming item 9
Consumer : Consuming item 5
Consumer : Consuming item 8
Consumer : Consuming item 9
Consumer : Consuming item 8



*/