Java 实现生产者与消费者问题

本文探讨了经典的生产者与消费者问题,通过使用Java并发工具Semaphore来实现进程间的同步。在有限的缓冲区中,多个生产者与消费者进程如何避免竞态条件,确保数据正确性和进程公平性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

生产者与消费者问题

问题简述:

  • 一群生产者进程在生产产品,并将这些产品提供给消费者去消费。为了使生产者进程与消费者进程能够并发进行,在两者之间设置一个具有n个缓冲区的缓冲池,生产者进程将产品放入一个缓冲区中;消费者可以从一个缓冲区取走产品去消费。尽管所有的生产者进程和消费者进程是以异方式运行,但它们必须保持同步:当一个缓冲区为空时不允许消费者去取走产品,当一个缓冲区满时也不允许生产者去存入产品。

具体实现:

package producterComsumer;

import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.Semaphore;

public class SemaphorePC  {

    public static int count = 0;
    public static int band = 0;
    public Random random = new Random();

    public static int buffer[] = new int[10];  //缓存区
    public static int position = 0; //缓存区下标
    LinkedList<Integer> goods = new LinkedList<Integer>();

    final Semaphore notFull = new Semaphore(10);
    final Semaphore notEmpty = new Semaphore(0);
    final Semaphore mutex = new Semaphore(1);
    
    public static void main(String[] args){

        SemaphorePC pc = new SemaphorePC();

       
        for(int i=0;i<10;i++){   //初始化缓存区
            buffer[i] = -1;
        }
        //while(true){
            new Thread(pc.new Producer()).start();
            new Thread(pc.new Consumer()).start();
            new Thread(pc.new Producer()).start();
            new Thread(pc.new Consumer()).start();
            new Thread(pc.new Producer()).start();
            new Thread(pc.new Consumer()).start();
        //}

       // new Thread(pc.new Producer()).start();


    }

    public void print(){
        for(int i=0;i<10;i++){
            if(buffer[i]!=-1)
                System.out.printf("%10d",buffer[i]);
            else
                System.out.print("      "+null);
        }
        System.out.println("\n");
        //createAndShowGUI(buffer);
    }

    class Producer implements Runnable{


        public Producer(){}
        @Override
        public void run() {
            for (int i = 0; i < 30; i++) {
                try {
                    Thread.sleep(random.nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    notFull.acquire();
                    mutex.acquire();
                    count++;
                    band++;
                    while(true){
                        //position++;
                        if(buffer[position=random.nextInt(10)]  == -1){
                            buffer[position] = band;
                            break;
                        }
                               // position = position %10;
                    }
                    String name = Thread.currentThread().getName();
                    if(name.equals("Thread-0")){
                        name = "producter 1 ";
                    }
                    else if(name.equals("Thread-2")){
                        name = "producter 2 ";
                    }
                    else if(name.equals("Thread-4")) {
                        name = "producter 3 ";
                    }
                    System.out.println(name+"生产了i一个商品"+band);
                    print();
                    //goods.add(band);
                    //System.out.println("生产者生产了一个商品,ID:"+band);
                    //System.out.println(Thread.currentThread().getName()
                    //        + "目前总共有" + count+"的商品");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    mutex.release();
                    notEmpty.release();
                }
            }

        }
    }

    class  Consumer implements Runnable{


        @Override
        public void run() {
            for(int i=0;i<30;i++){

            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            try {
                notEmpty.acquire();
                mutex.acquire();
                count--;
                int temp;
                while(true){
                    //position++;
                    if(buffer[position=random.nextInt(10)]  != -1){
                        temp = buffer[position];
                        buffer[position] = -1;
                        break;
                    }
                    // position = position %10;
                }
                //System.out.println("生产者生产了一个商品"+band);

                String name = Thread.currentThread().getName();
                if(name.equals("Thread-1")){
                    name = "comsumer 1 ";
                }
                else if(name.equals("Thread-3")){
                    name = "comsumer 2 ";
                }
                else if(name.equals("Thread-5")) {
                    name = "comsumer 3 ";
                }


                System.out.println(name+"消耗了商品 "+temp);
                print();   //输出
                //goods.remove(0);
                //System.out.println(Thread.currentThread().getName()
                //        + "目前总共有" + count);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                mutex.release();
                notFull.release();
            }
        }


    }
    }

}





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值