生产者消费者问题PV操作实现(Java)

import java.util.Scanner;


//模拟生产者与消费者案例
public class Test {
	public static void main(String[] args) {
		int pro, con;
		Scanner input = new Scanner(System.in);
		System.out.print("请输入生产者数目:");
		pro = input.nextInt();
		System.out.print("请输入消费者数目:");
		con = input.nextInt();
		for (int i = 0; i < pro; i++) {
			new Thread(new Producer(), "生产者" + Integer.toString(i) + "号").start();
		}
		for (int i = 0; i < con; i++) {
			new Thread(new Consumer(), "消费者者" + Integer.toString(i) + "号").start();
		}
	}
}

//全局变量
class Global {
	public static Semaphore empty = new Semaphore(5);
	public static Semaphore full = new Semaphore(0);
	public static Semaphore mutex = new Semaphore(1);
	public static int count = 0;

	//随机等待
	public static void naps() {
		try {
			Thread.sleep((int) (2000 * Math.random()));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
		
}

//生产者
class Producer implements Runnable {
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		Global.naps();
		System.out.println(Thread.currentThread().getName() + "  生产出一个商品...");
		Global.empty.P();
		Global.mutex.P();
		Global.naps();
		System.out.println(Thread.currentThread().getName() + "  将产品放入缓冲区--缓冲区剩余 " 
				+ (++Global.count) + " 个产品");
		Global.mutex.V();
		Global.full.V();
		
	}
}

//消费者
class Consumer implements Runnable {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		Global.naps();
		Global.full.P();
		Global.mutex.P();
		Global.naps();
		System.out.println(Thread.currentThread().getName() + "  从缓冲区取出一个产品--缓冲区剩余 "
				+ (--Global.count) + " 个产品");
		Global.mutex.V();
		Global.empty.V();
		System.out.println(Thread.currentThread().getName() + "  消费一个商品...");

	}
}

//信号量
class Semaphore {
	public int value;

	public Semaphore(int value) {
		super();
		this.value = value;
	}
	//P操作
	public synchronized final void P() {
		// TODO Auto-generated method stub
		value--;
		if(value < 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	//V操作
	public synchronized final void V() {
		// TODO Auto-generated method stub
		value++;
		if (value <= 0) {
			this.notify();
		}
	}
}

 

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