多線程——生產者消費者問題


package com.yanan.java3;

/**
 * Created by zhangyanana    on 2017/3/4.
 */
/*
生產者(Productor)將產品交給店員(Clerk),而消費者(Customer)從店員處取走產品,
店員一次只能持有固定數量的產品(比如:20),如果生產者試圖生產更多的產品,店員會叫生產者停一下,
如果店中有空位放產品了再通知生產者繼續生產;如果店中沒有產品了,店員會告訴消費者等一下,
如果店中有產品了再通知消費者來取走產品
    分析: 1.是否設計多線程?是,生產者,消費者
         2.是否涉及到共享數據?有!考慮線程的安全
         3.此共享數據是誰?即為產品的數量
         4.是否設計線程的通信?存在生產者與消費者的通信

 */

public class TestProduceConsume {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Produtor p1 = new Produtor(clerk);
        Consumer c1 = new Consumer(clerk);
        Thread t1 = new Thread(p1);
        Thread t2 = new Thread(c1);
        t1.setName("生產者1");
        t2.setName("消費者1");
        t1.start();
        t2.start();

    }
}

class Clerk {
    //商品容量
    int capacity = 20;
    //當前商品數量
    int product = 0;

    public synchronized void addProduct() {//生產產品
        if (product >= 20) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            product++;
            System.out.println(Thread.currentThread().getName() + ":生產了" + product + "個產品");
            notifyAll();
        }
    }

    public synchronized void consumeProduct() {//消費產品
        if (product <= 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + ":消費了" + product + "個產品");
            product--;
            notifyAll();
        }
    }


}

class Produtor implements Runnable {
    Clerk clerk;

    public Produtor(Clerk clerk) {
        this.clerk = clerk;
    }

    public void run() {
        System.out.println("生產者生產產品");
        while (true) {
            try {//sleep一下,讓效果更明顯
                Thread.currentThread().sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.addProduct();
        }
    }

}

class Consumer implements Runnable {
    Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    public void run() {
        System.out.println("消費者消費產品");
        while (true) {
            try {
                Thread.currentThread().sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.consumeProduct();
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM