进程同步-生产者和消费者(PV操作实现——java多线程模拟)

进程同步-生产者和消费者(PV操作实现——java多线程模拟)

目录

  • 进程同步-生产者和消费者PV操作实现java多线程模拟
    • 目录
    • 生产者和消费者概述
    • PV操作解决生产者和消费者
    • 任务要求
    • 程序代码
    • 运行结果

生产者和消费者概述

生产者消费者问题(英语:Producer-consumer problem),也称有限缓冲问题(英语:Bounded-buffer problem),是一个多线程同步问题的经典案例。该问题描述了两个共享固定大小缓冲区的线程——即所谓的“生产者”和“消费者”——在实际运行时会发生的问题。生产者的主要作用是生成一定量的数据放到缓冲区中,然后重复此过程。与此同时,消费者也在缓冲区消耗这些数据。该问题的关键就是要保证生产者不会在缓冲区满时加入数据,消费者也不会在缓冲区中空时消耗数据。——[百度百科]

PV操作解决生产者和消费者

semaphore empty = 6; //缓冲区初始空位置数为6
semaphore full = 0; //缓冲区初始满位置数为0
semaphore mutex = 1; //缓冲区互斥

生产者
P(empty);
P(mutex);
生产者生产食物;
V(mutex);
V(full);

消费者
P(full);
P(mutex);
消费者消费食物;
V(mutex);
V(empty);

任务要求

首先要写出PV操作的java代码,因为是原子操作,所以要加锁(synchronized)
代码如下

//信号量减一,若信号量小于0,本线程阻塞。
synchronized void P(Semaphore S) 
    {
        S.value--;
        if(S.value < 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
//信号量加一,若信号量依旧<=0,便将阻塞队列里一线程唤醒
synchronized void V(Semaphore S)
    {
        S.value++;
        if(S.value <= 0){
            this.notify();
        }

    }

因为本文的目的是使用信号量操作实现生产者和消费者,所以只在PV操作上加锁,其他地方不使用加锁。
信号量定义如下

class Semaphore
{
    int value;
    Semaphore(int value)
    {
        this.value = value;
    }

}

缓冲区buffer类里使用了双向链表,易于完成食品的put和get操作
部分代码如下

    LinkedList list = new LinkedList();
    Semaphore empty = new Semaphore(6);
    Semaphore full = new Semaphore(0);
    Semaphore mutex = new Semaphore(1);

    void put(Food food, String name)
    {
        P(empty);
        P(mutex);
        list.addLast(food);
        System.out.println(name + "生产出" + food);
        V(mutex);
        V(full);
    }

    void get(String name)
    {
        P(full);
        P(mutex);
        Food food = list.getFirst();
        System.out.println(name + "消费了" + food);
        list.removeFirst();
        V(mutex);
        V(empty);
    }

程序代码

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

class Semaphore
{
    int value;
    Semaphore(int value)
    {
        this.value = value;
    }

}

class Food
{
    int id = 0;
    Food(int id)
    {
        this.id = id;
    }
    public String toString()
    {
        return "食品"+id;
    }
}

class Buffer
{
    LinkedList list = new LinkedList();
    Semaphore empty = new Semaphore(6);
    Semaphore full = new Semaphore(0);
    Semaphore mutex = new Semaphore(1);

    void put(Food food, String name)
    {
        P(empty);
        P(mutex);
        list.addLast(food);
        System.out.println(name + "生产出" + food);
        V(mutex);
        V(full);
    }

    void get(String name)
    {
        P(full);
        P(mutex);
        Food food = list.getFirst();
        System.out.println(name + "消费了" + food);
        list.removeFirst();
        V(mutex);
        V(empty);
    }

    synchronized void P(Semaphore S) 
    {
        S.value--;
        if(S.value < 0){
            try {
                System.out.println(Thread.currentThread().getName() + "被堵塞");
                this.wait();
                System.out.println(Thread.currentThread().getName() + "被激活");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    synchronized void V(Semaphore S)
    {
        S.value++;
        //System.out.println("");
        if(S.value <= 0){
            this.notify();
        }

    }
}

//生产者发出50个请求,每次间隔时间100-200ms
class Produce implements Runnable
{
    Buffer buffer = null;
    Produce(Buffer buffer)
    {
        this.buffer = buffer;
    }
    @Override
    public void run() {
        for(int i=0; i<50; i++)
        {
            Random rand = new Random();
            Food food = new Food(i);
            buffer.put(food, Thread.currentThread().getName());
            try {
                Thread.sleep(rand.nextInt(100) + 100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

//消费者发出10个请求,每次间隔时间为500-1500ms
class Consumer implements Runnable
{

    Buffer buffer = null;
    Consumer(Buffer buffer)
    {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for(int i=0; i<10; i++)
        {
            Random rand = new Random();
            buffer.get(Thread.currentThread().getName());
            try {
                Thread.sleep(rand.nextInt(1000) + 500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

public class Test1 {

    //三个消费者线程,一个生产者线程
    public static void main(String[] args) {
        Buffer buff = new Buffer();
        Consumer consumer = new Consumer(buff);
        Produce prod = new Produce(buff);
        Consumer consumer2 = new Consumer(buff);
        new Thread(prod).start();
        new Thread(consumer).start();
        new Thread(consumer2).start();
        new Thread(new Consumer(buff)).start();
    }

}

运行结果

进程同步-生产者和消费者(PV操作实现——java多线程模拟)_第1张图片

你可能感兴趣的:(操作系统)