import java.util.Random;

public class producer_consumer_s {
    static public  int the_count=10;
    static  public  int the_number=0;
    static public boolean is_producing=true;   //The Semaphore
    public static void main(String[] args) {
        Producer p1 = new Producer();
        Consumer c1 = new Consumer();
        p1.start();
        c1.start();
    }
}

class Consumer extends Thread {

    public Consumer() {
    }

    public void run() {
        while (true) {
            if (producer_consumer_s .the_number == producer_consumer_s .the_count) {
                System.out.println("Consumer #" + producer_consumer_s .the_number);
                return;
            } else {
                if (!producer_consumer_s .is_producing) {   //New Number Available
                    System.out.println("Consumer #" + producer_consumer_s .the_number);
                    producer_consumer_s .is_producing = true;
                } else {
                    try {
                        sleep(new Random().nextInt(100)+10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

class Producer extends Thread {

    public Producer() {
    }

    public void run() {
        while (true) {
            if (producer_consumer_s .the_number == producer_consumer_s .the_count) return;
            else {
                if (producer_consumer_s .is_producing) {   //Produce another number
                    producer_consumer_s .the_number++;
                    System.out.println("Producer #" + producer_consumer_s .the_number);
                    producer_consumer_s .is_producing = false;
                } else {
                    try {
                        sleep(new Random().nextInt(100)+10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

A Run