多线程解决生产者/消费者问题
这是本学期的操作系统课程的一个上机实验,用多线程来解决生产者消费者问题,源代码如下,我是初学者,尽量写的浅显些,尽量把注释写的完善些,如果有什么看不懂的可以留言,大家一起学习。
public class Semaphore {
int value;
public Semaphore(int v){this.value = v;}
//定义P原语操作
public synchronized void p(){
value = value-1;
if (value < 0){
try{
this.wait();
}
catch (InterruptedException e){
}
}
}
//定义V原语操作
public synchronized void v(){
value = value+1;
if (value <= 0){
this.notify();
}
}
}
public class Producer extends Thread{
private Semaphore[] s;
private int i;
public Producer(int i,Semaphore[] sp){
this.i = i;
this.s = sp;
}
public void run() {
while(true){
s[1].p();
s[0].p();
System.out.println("produce "+i++);
try {
Thread.sleep(30);
}
catch (InterruptedException e) {}
s[0].v();
s[2].v();
}
}
}
public class Consumer extends Thread {
private Semaphore[] s;
private int i;
public Consumer(int i,Semaphore[] sp){
this.i = i;
this.s = sp;
}
public void run() {
while(true){
s[2].p();
s[0].p();
System.out.println("consumer "+i++);
try {
Thread.sleep((long)(Math.random()*100));
}
catch (InterruptedException e) {}
s[0].v();
s[1].v();
}
}
}
public class pc {
public static void main(String[] args) {
int mutex = 1;//互斥的信号量,生产者消费者不能同时访问缓冲区
int empty = 3;//表示空闲的缓冲区的数目,初始值为3
int full = 0;//full表示有数据的缓冲区的数目,初始值为0
Semaphore[] s = new Semaphore[3];
s[0] = new Semaphore(mutex);
s[1] = new Semaphore(empty);
s[2] = new Semaphore(full);
Producer p = new Producer(0,s);
Consumer c = new Consumer(0,s);
Thread pp = new Thread(p);
Thread cc = new Thread(c);
Thread pp1 = new Thread(p);
Thread cc1 = new Thread(c);
cc1.start();
pp1.start();
pp.start();
cc.start();
}
}