【发布时间】:2019-08-07 10:01:56
【问题描述】:
我想使用 2 个线程来实现循环缓冲区。一个线程从缓冲区读取,另一个线程写入缓冲区,如下所示:
假设进程 P 是写进程,进程 Q 是读进程。
从主类启动两个进程后,我如何将每次我想写入缓冲区的值传递给进程 P(写入器)?同样,我如何要求进程 Q(读取器)从缓冲区中读取(即如何调用它以返回它从缓冲区中读取的值)?
我很困惑,因为这两个过程的实现都是在 run() 方法中完成的,而这个方法是在我们发出 .start() 命令时执行的。但是,一旦启动,我们如何才能在运行模式下继续传递和读取参数。
我正在关注以下问题中提到的以下示例中的实现: Circular Buffer with Threads Consumer and Producer: it get stucks some executions
共享变量:
public class BufferCircular {
volatile int[] array;
volatile int p;
volatile int c;
volatile int nElem;
public BufferCircular(int[] array) {
this.array = array;
this.p = 0;
this.c = 0;
this.nElem = 0;
}
public void writeData (int data) {
this.array[p] = data;
this.p = (p + 1) % array.length;
this.nElem++;
}
public int readData() {
int data = array[c];
this.c = (c + 1) % array.length;
this.nElem--;
return data;
}
}
写入过程:
public class Producer extends Thread {
BufferCircular buffer;
int bufferTam;
int contData;
public Productor(BufferCircular buff) {
this.buffer = buff;
this.bufferTam = buffer.array.length;
this.contData = 0;
}
public void produceData() {
this.contData++;
this.buffer.writeData(contData);
}
public void run() {
for (int i = 0; i < 500; i++) {
while (this.buffer.nElem == this.bufferTam) {
Thread.yield();
}
this.produceData();
}
}
}
阅读器进程:
public class Consumer extends Thread {
BufferCircular buffer;
int cont;
public Consumer(BufferCircular buff) {
this.buffer = buff;
this.cont = 0;
}
public void consumeData() {
int data = buffer.readData();
cont++;
System.out.println("data " + cont + ": " + data);
}
public void run() {
for (int i = 0; i < 500; i++) {
while (this.buffer.nElem == 0) {
Thread.yield();
}
this.consumeData();
}
}
}
主要:
public class Main {
public static void main(String[] args) {
Random ran = new Random();
int tamArray = ran.nextInt(21) + 1;
int[] array = new int[tamArray];
BufferCircular buffer = new BufferCircular(array);
Producer producer = new Producer (buffer);
Consumer consumer = new Consumer (buffer);
producer.start();
consumer.start();
try {
producer.join();
consumer.join();
} catch (InterruptedException e) {
System.err.println("Error with Threads");
e.printStackTrace();
}
}
}
【问题讨论】:
标签: java multithreading circular-buffer