生產者消費者代碼簡單示例

public class ProducerAndConsumer {

    private static final Object lock = new Object();

    private static int count = 0;
    private static int FULL = 10;


    public static void main(String[] args) {

        new Thread(new Producer()).start();
        new Thread(new Producer()).start();
        new Thread(new Producer()).start();
        new Thread(new Producer()).start();
        new Thread(new Consumer()).start();

    }


    static class Producer implements Runnable {

        @Override
        public void run() {
            while (true) {
                sleep();
                synchronized (lock) {
                    while (count == FULL) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    count ++;
                    System.out.println(Thread.currentThread().getName() + "生產者生產,目前總共有:" + count);
                    lock.notifyAll();
                }
            }
        }
    }


    static class Consumer implements Runnable {
        @Override
        public void run() {
            sleep();
            while (true) {
                synchronized (lock) {
                    while (count == 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    count --;
                    System.out.println(Thread.currentThread().getName() + "消費者消費,目前總共有:" + count);
                    lock.notifyAll();
                }
            }
        }
    }

    /**
     * 主要爲了演示效果
     */
    private static void sleep() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {}
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章