Java管程解决生产者消费者问题

同样是实验存档。//。。

依然以生产者消费者问题作为背景。

管程(=“资源管理程序”)将资源和对资源的操作封装起来,资源使用者通过接口操作资源就ok,不用去考虑进程同步的问题。

管程:

package entity.producerconsumer;

public class Monition {
    private Buffer buffer;

    public Monition(int bufferSize) {
        buffer = new Buffer(bufferSize);
    }

    /**
     * 如果放入产品成功返回 true
     * @return
     */
    public synchronized boolean put() {
        if (buffer.notFull()) {
            buffer.putItem();
            return true;
        }
        return false;
    }

    /**
     * 如果取出产品成功返回 true
     * @return
     */
    public synchronized boolean get() {
        if (buffer.notEmpty()) {
            buffer.getItem();
            return true;
        }
        return false;
    }

    public String getStatus() {
        return "" + buffer;
    }
}

 生产者 & 消费者:

package entity.producerconsumer;

public class Produc implements Runnable {
    /**
     * 统计生产者数量
     */
    private static int total = 0;
    /**
     * 生产者个体的 id
     */
    private int id;

    private Monition PC;

    public Produc(Monition monition) {
        id = ++total;
        PC = monition;
    }

    @Override
    public void run() {
        while (true) {
            if (PC.put()) {
                // 如果操作成功打印缓冲区状态
                System.out.println(id + " 号生产者: " + PC.getStatus());
            }
        }
    }
}

/

package entity.producerconsumer;

public class Consu implements Runnable {
    /**
     * 统计消费者数量
     */
    private static int total = 0;
    /**
     * 消费者个体的 id
     */
    private int id;

    private Monition PC;

    public Consu(Monition monition) {
        id = ++total;
        PC = monition;
    }

    @Override
    public void run() {
        while (true) {
            if (PC.get()) {
                // 如果操作成功打印缓冲区状态
                System.out.println(id + " 号消费者: " + PC.getStatus());
            }
        }
    }
}

/

Buffer.java

 

测试:

package test;

import entity.producerconsumer.Consu;
import entity.producerconsumer.Monition;
import entity.producerconsumer.Produc;

public class MonitionTest {
    public static void main(String[] args) {
        Monition PC = new Monition(10);
        // 创建 5 个生产者和 5 个消费者
        for (int i = 0; i != 5; ++i) {
            new Thread(new Produc(PC)).start();
            new Thread(new Consu(PC)).start();
        }
    }
}

 

posted @ 2017-11-20 16:54  xkfx  阅读(1566)  评论(0编辑  收藏  举报