天天看點

Java多線程-生産者與消費者

Java多線程生産者與消費者,準确說應該是“生産者-消費者-倉儲”模型,使用了倉儲,使得生産者消費者模型就顯得更有說服力。

對于此模型,應該明确一下幾點:

1、生産者僅僅在倉儲未滿時候生産,倉滿則停止生産。

2、消費者僅僅在倉儲有産品時候才能消費,倉空則等待。

3、當消費者發現倉儲沒産品可消費時候會通知生産者生産。

4、生産者在生産出可消費産品時候,應該通知等待的消費者去消費。

一、倉庫

可以選擇有線程安全的PriorityBlockingQueue也可以使用普通的list,為了更加展現多線程這裡使用沒有線程安全的普通list

private static LinkedList<String> list = new LinkedList<String>();
           

使用LinkedList是因為删除時更加友善。

二、生産者

/**
     * 生産者
     * 
     * @author Administrator
     * 
     */
    static class ProductThread implements Runnable {

        private int count = ;
        public ProductThread(int count) {
            this.count = count;
        }

        @Override
        public void run() {
            while(true){
                synchronized (list) {
                    if(list.size()>){//容量達到20以上,等待消費
                        try {
                            list.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    for(int i = ;i<count ;i++){
                        System.out.println("生産了一個産品---"+i);
                        list.add("str"+i);
                    }
                    list.notifyAll();
                }
            }
        }

    }
           

三、消費者

static class CustomerThread implements Runnable {

        private int count = ;
        public CustomerThread(int count) {
            this.count = count;
        }

        @Override
        public void run() {
            while(true){
                synchronized (list) {
                    if(list.size() < count){
                        System.out.println("容器中數量不夠," + list.size());
                        try {
                            list.wait();// 等待
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    for(int i =;i<=count;i++){
                        String remove = list.remove();
                        System.out.println("消費掉一個産品--"+remove);
                    }
                    list.notify();
                }
            }
        }

    }
           

四、測試類

public static void main(String[] args) {
        // 每次生産10個
        Thread proTh = new Thread(new ProductThread());
        // 每次消費6個
        Thread cusTh = new Thread(new CustomerThread());
        proTh.start();
        cusTh.start();
    }
           

這樣一個簡單的生産者消費者模型就完成了。