Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.LinkedList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> stack = new LinkedList<Integer>();
        Producer producer = new Producer(stack);
        Consumer consumer = new Consumer(stack);
        producer.start();
        consumer.start();
    }
}

class Producer extends Thread {
    public Producer(List<Integer> s) {
        mStack = s;
    }

    List<Integer> mStack = null;
    int mNumber = 0;

    @Override
    public void run() {
        while (true) {
            synchronized (mStack) {
                while (!mStack.isEmpty()) {
                    try {
                        mStack.wait(); // this.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                mNumber++;
                System.out.println("Producer generates number:" + mNumber);
                mStack.add(mNumber);
                mStack.notifyAll();// this.notifyAll();
            }
        }
    }
}

class Consumer extends Thread {
    public Consumer(List<Integer> s) {
        mStack = s;
    }

    List<Integer> mStack = null;

    @Override
    public void run() {
        while (true) {
            synchronized (mStack) {
                while (mStack.isEmpty()) {
                    try {
                        mStack.wait(); // this.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                int number = ((LinkedList<Integer>) mStack).removeLast();
                System.out.println("Consumer consumes number:" + number);
                mStack.notifyAll();// this.notifyAll();
            }
        }
    }
}