Loading... ### 代码 package 生产者_消费者问题; import java.util.Random; public class Semaphore { int value; Semaphore(int value) { this.value = value; } } class Buffer { static int n=5;//缓冲区大小 int[] buffer=new int[n]; Semaphore empty = new Semaphore(n); Semaphore full = new Semaphore(0); Semaphore mutex = new Semaphore(1); int data_p=1; int data_c=0; //信号量减一,若信号量小于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(); } } void producer(int i) { P(empty); if(buffer[i]==0) { P(mutex); buffer[i]=data_p; System.out.println("生产了"+i); V(mutex); } V(full); } void consumer(int j) { P(full); if(buffer[j]==1) { P(mutex); buffer[j]=data_c; System.out.println("消费了"+j); V(mutex); } V(empty); } } //生产者发出5个请求,每次间隔时间100ms class Produce implements Runnable { Buffer buffer = null; Produce(Buffer buffer) { this.buffer = buffer; } public void run() { for(int i=0; i<5; i++) { Random rand = new Random(); buffer.producer(rand.nextInt(5)); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //消费者发出5个请求,每次间隔时间为500ms class Consumer implements Runnable { Buffer buffer = null; Consumer(Buffer buffer) { this.buffer = buffer; } public void run() { for(int i=0; i<5; i++) { Random rand = new Random(); buffer.consumer(rand.nextInt(5)); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } package 生产者_消费者问题; public class main { public static void main(String[] args) { Buffer buff = new Buffer(); Consumer consumer = new Consumer(buff); Produce prod = new Produce(buff); new Thread(prod).start(); new Thread(consumer).start(); } } ### 输出结果 ![](https://i.loli.net/2019/03/27/5c9b7561cefa8.png) ![](https://i.loli.net/2019/03/27/5c9b7561e3c3e.png) ![](https://i.loli.net/2019/03/27/5c9b7561e3ebd.png) ![](https://i.loli.net/2019/03/27/5c9b7561e3eb8.png) ![](https://i.loli.net/2019/03/27/5c9b756205578.png) Last modification:March 27th, 2019 at 09:09 pm © 允许规范转载 Support If you think my article is useful to you, please feel free to appreciate ×Close Appreciate the author Sweeping payments
Comment here is closed