1. 程式人生 > 實用技巧 >實現生產者消費者問題

實現生產者消費者問題

package com.bzw.multithreaded;

import java.util.LinkedList;
import java.util.Queue;

public class ProducedCustom {

    public static void main(String[] args) {

        Produce produce = new Produce();

        Producer producer = new Producer(produce);
        Customer customer = new Customer(produce);
        producer.start();
        customer.start();


    }


}

class Produce{ private final static int size = 20; Queue<Integer> queue = new LinkedList<>(); public synchronized void put(int i){ if (queue.size() >= size ){ System.out.println("倉庫已滿,停止生產"); try { wait(); } catch
(InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "生產者生產了第" + i + "件商品"); queue.add(i); notify(); } public synchronized int get(){ if (queue.isEmpty()){ System.out.println(
"庫存為空,停止銷售"); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int val = queue.poll(); System.out.println(Thread.currentThread().getName() + "消費者購買了第" + val + "件商品"); notify(); return val; } } class Producer extends Thread{ private Produce produce; public Producer(Produce produce){ this.produce = produce; } public void run(){ for (int i=0;i<=40;i++){ produce.put(i); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } } } } class Customer extends Thread{ private Produce produce; public Customer(Produce produce){ this.produce = produce; } public void run(){ while (true){ produce.get(); } } }

  這裡用來一個Produce類表示倉庫,用佇列來儲存資料,生產者和消費者都是通過倉庫間接通訊。當倉庫滿時,讓生產者wait();當倉庫空時,讓消費者wait()。在消費者和生產者中的run方法中都是呼叫倉庫中的方法,實現資料共享。